Reputation: 3
Below is my Json string
Json String
{
"RestResponse": {
"messages": [
"Country found matching code [IN]."
],
"result": {
"name": "India",
"alpha2_code": "IN",
"alpha3_code": "IND"
}
}
}
I made these class in Xamarin but is not parsing the Json to objects, Please guide.
public class Country
{
[JsonProperty(PropertyName = "RestResponse")]
public List<myRestResponse> RestResponse { get; set; }
}
public class myRestResponse
{
[JsonProperty(PropertyName = "messages")]
public List<string> messages { get; set; }
[JsonProperty(PropertyName = "result")]
public List<Result> result { get; set; }
}
public class Result
{
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "alpha2_code")]
public string alpha2_code { get; set; }
[JsonProperty(PropertyName = "alpha3_code")]
public string alpha3_code { get; set; }
}
I am Deserializing using below code
var content = await response.Content.ReadAsStringAsync();
Country country = JsonConvert.DeserializeObject<Country>(content);
Upvotes: 0
Views: 89
Reputation: 362
Your class definitions don't match with the response data. You can easily create class definition using some online tool. If you are using Visual Studio then you can simply use Paste Special option from Edit menu. Rember that, you have to copy the response string at first before doing the paste.
Upvotes: 0
Reputation: 8561
You JSON is not correct format according to your class structure. There are two issues with JSON. According to your class structure you are trying to DeSerialize, property'RestResponse' is an array but in your JSON it is not. Another one is the property 'result', which is again an array but in your JSON it is not. Either update your class structure according to your JSON format or please try below JSON,
{
"RestResponse": [
{
"messages": [ "Country found matching code [IN]." ],
"result": [
{
"name": "India",
"alpha2_code": "IN",
"alpha3_code": "IND"
}
]
}
]
}
If you want to update your class structure please copy below classes,
public class Result
{
public string name { get; set; }
public string alpha2_code { get; set; }
public string alpha3_code { get; set; }
}
public class RestResponse
{
public List<string> messages { get; set; }
public Result result { get; set; }
}
public class RootObject
{
public RestResponse RestResponse { get; set; }
}
Upvotes: 0
Reputation: 9650
Using a tool such as http://json2csharp.com/ helps to define your classes.
This gives the result of
public class Result
{
public string name { get; set; }
public string alpha2_code { get; set; }
public string alpha3_code { get; set; }
}
public class RestResponse
{
public List<string> messages { get; set; }
public Result result { get; set; }
}
public class Country
{
public RestResponse RestResponse { get; set; }
}
So you can see that your Country class (Root object) should not have a list.
And RestResponse should only contain a single Result object, again not a list.
Upvotes: 2