locked
How can I deserialise an array of Json objects RRS feed

  • Question

  • User-963208184 posted

    Hi All,

    I have a called a method that returns an array of data in the form

    [JSON]
      [0]
        prop1 : "value"
        .........
      [1]
        prop1 : "value"
        .......
      [2]
        .......

    each item of the array have the same properties.

    I have created a class that has all the properties of an array item and a  further class with a single property of type IEnumerable<propertiesClass>.

    I thought I'd be able to get away with something like:

     IEnumerable<propertiesClass> = new JavaScriptSerializer().Deserialize<IEnumerable<propertiesClass>>(returnedString);

    Tuesday, June 2, 2015 11:56 AM

All replies

  • User-271186128 posted

    Hi billcrawley,

    As for this issue, will you please tell me how do you generate the JSON string? <o:p></o:p>

    I thought I'd be able to get away with something like:

     IEnumerable<propertiesClass> = new JavaScriptSerializer().Deserialize<IEnumerable<propertiesClass>>(returnedString);

    Besides, from your description, if you mean you don't want to use JavaScriptSerializer().Deserialize() method, I suppose you could try to use JsonConvert.SerializeObject and

    JsonConvert.DeserializeObject method. Here is a sample, please refer to it:

                List<User> list = new List<WebApplication1.Test1.User>();
                list.Add(new User() { UserID = 1001, UserName = "AAA" });
                list.Add(new User() { UserID = 1002, UserName = "BBB" });
                list.Add(new User() { UserID = 1003, UserName = "CCC" });
                list.Add(new User() { UserID = 1004, UserName = "DDD" });
                list.Add(new User() { UserID = 1005, UserName = "EEE" });
    
                string str1 = JsonConvert.SerializeObject(list);
                TextBox1.Text = str1; //output:[{"UserID":1001,"UserName":"AAA"},{"UserID":1002,"UserName":"BBB"},{"UserID":1003,"UserName":"CCC"},{"UserID":1004,"UserName":"DDD"},{"UserID":1005,"UserName":"EEE"}]
                
                List<User> list2 = JsonConvert.DeserializeObject<List<User>>(str1);
                TextBox2.Text = list2[2].UserName;

    If you don't want to use DeserializeObject() method, I suppose you need to use String.Split() method to split the string and use for loop to get the special data.

    Best Regards,
    Dillion

    Wednesday, June 3, 2015 12:07 AM
  • User753101303 posted

    Hi,

    Some more context could still help. In most cases it should be handled for you. For example if you are calling a service you get back a string if working at a low level but if using a client such as HttpClient then deserialization is handled for you.

    Make sure you don't try to code something that could have been done automatically for you...

    Wednesday, June 3, 2015 12:26 PM