我从http请求中收到一个Json字符串,看起来像这样:
{
"info":
[
{
"calls":0,
"errors":"[error1, error2, error3]",
"messages":0,
"mail":3
}
],
"received":5,
"valid":3
}
Run Code Online (Sandbox Code Playgroud)
我试图反序列化的实体的结构大致相同
class ResponseEntity
{
private Info info;
private int received;
private int valid;
[JsonProperty("info")]
public Info Info
{
get { return info; }
set { info = value; }
}
[JsonProperty("valid")]
public int valid
{
get { return valid; }
set { valid = value; }
}
[JsonProperty("received")]
public int received
{
get { return received; }
set { received = value; }
}
public class Info
{
private int calls;
private List<string> errors;
private int messages;
private int mail;
[JsonProperty("calls")]
public int Calls
{
get { return calls; }
set { calls = value; }
}
[JsonProperty("messages")]
public int Messages
{
get { return messages; }
set { messages = value; }
}
[JsonProperty("errors")]
public List<string> Errors
{
get { return errors; }
set { errors = value; }
}
[JsonProperty("mail")]
public int Mail
{
get { return mail; }
set { mail = value; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我试图反序列化它虽然我得到一个例外
ResponseEntity ent = JsonConvert.DeserializeObject<ResponseEntity>(json) as ResponseEntity;
Cannot deserialize JSON array into type 'CSharpRestService.ResponseEntity+Info'.
Run Code Online (Sandbox Code Playgroud)
谁能看到我做错了什么?我在想'错误'json键搞砸了,但我也试过一个字符串数组.
我的测试代码不会使用嵌套的Info类进行编译(由于属性命名冲突),所以我从ResposeEntity类中删除了它.
除此之外,我修复了你的JSON的一些问题(你的信息对象是一个数组,你的错误数组中的字符串需要在引号中).
见下文:
JSON
{
info":
{
"calls":0,
"errors":["error1", "error2", "error3"],
"messages":0,
"mail":3
},
"received":5,
"valid":3
}
Run Code Online (Sandbox Code Playgroud)
类
class ResponseEntity
{
private Info info;
private int received;
private int valid;
[JsonProperty("info")]
public Info Info
{
get { return info; }
set { info = value; }
}
[JsonProperty("valid")]
public int Valid
{
get { return valid; }
set { valid = value; }
}
[JsonProperty("received")]
public int Received
{
get { return received; }
set { received = value; }
}
}
public class Info
{
private int calls;
private List<string> errors;
private int messages;
private int mail;
[JsonProperty("calls")]
public int Calls
{
get { return calls; }
set { calls = value; }
}
[JsonProperty("messages")]
public int Messages
{
get { return messages; }
set { messages = value; }
}
[JsonProperty("errors")]
public List<string> Errors
{
get { return errors; }
set { errors = value; }
}
[JsonProperty("mail")]
public int Mail
{
get { return mail; }
set { mail = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
测试代码
string json = "{\"info\":{\"calls\":0,\"errors\":[\"error1\", \"error2\", \"error3\"],\"messages\":0,\"mail\":3},\"received\":5,\"valid\":3}";
ResponseEntity ent = JsonConvert.DeserializeObject<ResponseEntity>(json) as ResponseEntity;
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
10351 次 |
| 最近记录: |