如何反序列化给JSON字符串到一个定义的类

问题描述:

下面是我的JSON字符串如何反序列化给JSON字符串到一个定义的类

JSON字符串

{ 
    "RestResponse": { 
    "messages": [ 
     "Country found matching code [IN]." 
    ], 
    "result": { 
     "name": "India", 
     "alpha2_code": "IN", 
     "alpha3_code": "IND" 
    } 
    } 
} 

我在Xamarin使这些类,但没有解析JSON的对象,请指导。

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; } 
} 

我使用下面的代码反序列化

var content = await response.Content.ReadAsStringAsync(); 
Country country = JsonConvert.DeserializeObject<Country>(content); 
+0

'RestResponse'不是首发的集合,并且也不是'result'。 – juharr

使用诸如http://json2csharp.com/之类的工具有助于定义您的课程。

这给出了

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; } 
} 

结果所以,你可以看到你的国家的类(根对象)不应该有一个列表。

RestResponse应该只包含一个Result对象,而不是一个列表。

你JSON是不是按你的类结构,正确的格式。 JSON有两个问题。根据你的类结构你试图DeSerialize,property'RestResponse'是一个数组,但是在你的JSON中它不是。另一个是属性“结果”,它又是一个数组,但在你的JSON中它不是。无论是根据您的JSON格式更新您的类结构或请尝试以下JSON,

{ 
 
    "RestResponse": [ 
 
    { 
 
     "messages": [ "Country found matching code [IN]." ], 
 
     "result": [ 
 
     { 
 
      "name": "India", 
 
      "alpha2_code": "IN", 
 
      "alpha3_code": "IND" 
 
     } 
 
     ] 
 
    } 
 
    ] 
 
}

如果您想更新您的类结构,请复制下面的类,

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; } 
} 

您的类定义与响应数据不匹配。您可以使用一些在线工具轻松创建类定义。如果您使用的是Visual Studio,那么您可以简单地使用粘贴特殊选项编辑菜单。注意到,你必须首先复制响应字符串,然后再进行粘贴。

enter image description here