简体   繁体   中英

json to C# object how to deserialize JSON

How to deserialize this json string in C#

{ "accountant": { "sysid": "1", "first_name": "Test", "last_name": "Test", "product_type": "Sample" } }

What I tried so far is using JsonConvert.DeserializeObject

var jsonObj = JsonConvert.DeserializeObject<AccountantData>(responseMessage);

this is my Model

public class AccountantData
{
    [JsonProperty("accountant")]
    public List<UserData> Accountant { get; set; }
}
public class UserData
{
    public UserData(int sysId, string firstName, string lastName, string productType)
    {
        SystemId = sysId;
        FirstName = firstName;
        LastName = lastName;
        ProductType = productType;
    }

    [JsonProperty("sysid")]
    public int SystemId { get; set; }

    [JsonProperty("first_name")]
    public string FirstName { get; set; }

    [JsonProperty("last_name")]
    public string LastName { get; set; }

    [JsonProperty("product_type")]
    public string ProductType { get; set; }
}

but this results to an error

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

Additional information: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.UserData]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) 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.

Your JSON input string is not correct. AccountantData uses List (Array) of UserData . Try this:

{
   "accountant":[
      {
         "sysid":"1",
         "first_name":"Test",
         "last_name":"Test",
         "product_type":"Sample"
      }
   ]
}

Update: If you are always going to have a single object of UserData then you can change your AccountantData class as:

public class AccountantData
{
  [JsonProperty("accountant")]
  UserData Accountant { get; set; }
}

Also, in case you will always have single UserData object and you have control of JSON data, then you can update your JSON input data to simpler format as below:

{
   "sysid":"1",
   "first_name":"Test",
   "last_name":"Test",
   "product_type":"Sample"
}

and then deserialize it like this:

var jsonObj = JsonConvert.DeserializeObject<UserData>(responseMessage);

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