简体   繁体   中英

How to Deserialize Json Object - C#

A web service returns JSON object as blew:

JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}"

I tried to Deserialize by doing this:

  1. Define the objects

     public class RootResponseClass { public ResponseParametersClass[] d { get; set; } } public class ResponseParametersClass { public string sname { get; set; } public string region { get; set; } public string name { get; set; } } 
  2. Write the Deserialize Method

      JavaScriptSerializer ser2 = new JavaScriptSerializer(); RootResponseClass obj = new RootResponseClass(); obj = ser2.Deserialize<RootResponseClass>(JsonString); 

But It is gives error "Cannot convert object of type 'System.String' to type 'NAS.Helpers.ResponseParametersClass[]", So how can i do it!

Solution

 public class RootResponseClass
    {
        public string d { get; set; }
    }

And for deserialize method :

JavaScriptSerializer ser2 = new JavaScriptSerializer();
RootResponseClass obj = new RootResponseClass();
obj = ser2.Deserialize<RootResponseClass>(JsonString);

List<ResponseParametersClass> obj2 = new List<ResponseParametersClass>();
obj2 = ser2.Deserialize<List<ResponseParametersClass>>(obj.d.ToString());

You can use the package using Newtonsoft.Json; for deserializing JSON

example

JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}";

var foo = JsonConvert.DeserializeObject<RootResponseClass>(JsonString);

foo is your deserialized object.

EDIT

As extra information why the initial way is not working is because your array is starting with quotes so its recognized as a string. After the "{"d": should be just [] instead of "[]"

Thanx Dnomyar96 for pointing that extra out.

Your Json string seems to contain another Json string. So in order to deserialize this, you'd need to deserialize as you're doing now, but change the ResponseParametersClass to string .

Then you'd need to deserialize the string you just got (as a List<ResponseParametersClass> ). So in this case you'd need to deserialize in two seperate steps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM