Reputation: 1740
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 (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.UserData]' 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) 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.
Upvotes: 0
Views: 1072
Reputation: 4098
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);
Upvotes: 1