locked
how to deserialize a json array with newton json RRS feed

  • Question

  • User450763225 posted

    Hi, I am trying to deserialize the below json array with newton json, however I got some trouble, please help.

    {
      'firstname': 'james',
      'lastname': 'james',
      'gender': 'M',
      'address': [
        'address1','1'
        'address2','2'
      ]
    }
    string json = File.ReadAllText(@"D:\project\JsonTest\JsonTest\Json.json");           
     List<ShippingInfo> shippingInfo = JsonConvert.DeserializeObject<List<ShippingInfo>>(json);
                Console.WriteLine("success");
    
            }
    
            public class ShippingInfo
            {
                public string firstname { get; set; }
                public string lastname { get; set; }
                public string gender { get; set; }
    
                public IList<address> address { get; set; }
            }
    
            public class address
            {
                public string address1 { get; set; }
                public string address2 { get; set; }
            }

    This is the error I got, 

     Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[JsonTest.Program+ShippingInfo]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
    To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

    Sunday, April 25, 2021 5:57 PM

All replies

  • User-1545767719 posted

    I am trying to deserialize the below json array with newton json

    First of all the "below json array" is  not correct as a JSON. Please make correction.

    Sunday, April 25, 2021 10:37 PM
  • User-939850651 posted

    Hi sdnd2000,

    The Json format uses "[ ]" to denote a collection, and "{ }" to denote an object. And use "," to separate each attribute or object.

    According to the results you need to return, your Json text is at least like this:

    [{
       'firstname': 'james',
       'lastname': 'james',
       'gender': 'M',
       'address': [{
          'address1':'1',
          'address2':'2'
        }]
     }]

    You could also refer and learn from w3schools json_arrays.

    Best regards,

    Xudong Peng

    Monday, April 26, 2021 5:32 AM