L
L
Leonid2020-09-08 11:59:31
JSON
Leonid, 2020-09-08 11:59:31

How to parse json in .net?

Forced to use DataContractJsonSerializer
such json class
{"ErrorMessage":""}

[DataContract]
    public class ResultScanResponse
    {
        [DataMember(Name = "ErrorMessage")]
        public string ErrorMessage { get; set; }
    }


the code
public static T Deserialize<T>(string aJSON) where T : new()
        {
            T deserializedObj = new T();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(aJSON));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(aJSON.GetType());
            deserializedObj = (T)ser.ReadObject(ms);
            ms.Close();
            return deserializedObj;
        }

when deserializing it says
"There was an error deserializing the object of type System.String. End element 'root' from namespace '' expected. Found element 'ErrorMessage' from namespace ''."

What's wrong with him?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2020-09-08
@caballero

public static T Deserialize<T>(string aJSON) where T : new()
{
       var ms = new MemoryStream(Encoding.UTF8.GetBytes(aJSON));
       var ser = new DataContractJsonSerializer(typeof(T));
       var deserializedObj = (T)ser.ReadObject(ms);
       ms.Close();
       return deserializedObj;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question