我从一个类似这样的 http 请求接收到一个 Json 字符串:
{
"info":
[
{
"calls":0,
"errors":"[error1, error2, error3]",
"messages":0,
"mail":3
}
],
"received":5,
"valid":3
}
我试图反序列化的实体的结构大致相同
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; }
}
}
}
当我尝试反序列化它时,虽然我遇到了异常
ResponseEntity ent = JsonConvert.DeserializeObject<ResponseEntity>(json) as ResponseEntity;
Cannot deserialize JSON array into type 'CSharpRestService.ResponseEntity+Info'.
谁能看到我做错了什么?我在想 'errors' json 键搞砸了,但我也尝试了一个字符串数组。
最佳答案
我的测试代码无法与嵌套的 Info 类一起编译(由于属性命名冲突),因此我将其从 ResposeEntity 类中删除。
除此之外,我还修复了您的 JSON 的一些问题(您的 info 对象是一个数组,并且您的 errors 数组中的字符串需要用引号引起来)。
见下文:
JSON
{
info":
{
"calls":0,
"errors":["error1", "error2", "error3"],
"messages":0,
"mail":3
},
"received":5,
"valid":3
}
类
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; }
}
}
测试代码
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;
希望这会有所帮助。
关于c# - json.net 将字符串反序列化为嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7181983/