question

YangZhang-8570 avatar image
0 Votes"
YangZhang-8570 asked YangZhang-8570 action

how to deserialize a json array with newton json

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


  static void Main(string[] args)
         {
             string json = @"{
   'firstname': 'james',
   'lastname': 'james',
   'gender': 'M',
   'address': [
     'address1','1'
     'address2','2'
   ]
 }";
              
             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; }
         }

Error: 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.

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered YangZhang-8570 commented

There are several issues, which were eliminated in the next sample:

 public class ShippingInfo
 {
     public string firstname { get; set; }
     public string lastname { get; set; }
     public string gender { get; set; }
    
     public address address { get; set; }
 }
    
 public class address
 {
     public string address1 { get; set; }
     public string address2 { get; set; }
 }
    
 . . .
    
 string json = @"{
    'firstname': 'james',
    'lastname': 'james',
    'gender': 'M',
    'address': {
       'address1':'1',
       'address2':'2'
    }
 }";
    
 ShippingInfo shippingInfo = JsonConvert.DeserializeObject<ShippingInfo>( json );
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.