繁体   English   中英

使用字符串数组反序列化JSON对象时发生异常

[英]Exception on deserialization of JSON object with string array

问题:

我需要反序列化JSON对象。 但是,看来对象中的字符串数组会导致异常,而我不知道为什么。

我使用了json.parser.online.frjson2csharp之类的工具来确保JSON的格式正确,反序列化的类也是正确的。 在这两种情况下,工具都可以,并且没有显示错误。 但是我仍然例外。

任何帮助,将不胜感激。

JSON:

{
"ID":123,
"Content":[ "{\"NewName\":\"asd\",\"Type\":\"2\"}]}" ],
"Notes":[""],
"Type":2,
"Subjects":"asd",
"Classes":"1",
"Name":"fdsgfd",
"Assign_Content":[
"[{\"Type\":\"text\",\"Text\":\"dfgfgs\"]"
],
"Creator":"example@example.com",
"isActive":"False",
"Editor":"example@example.com",
"CreatedDate":"2017-08-22T00:00:00",
"LastModifiedDate":"2017-08-22T00:00:00"
}

反序列化:

var task = JsonConvert.DeserializeObject<RootObject>(JSON);

类:

public class RootObject
{
    public int ID { get; set; }
    public List<string> Content { get; set; }
    public List<string> Notes { get; set; }
    public int Type { get; set; }
    public string Subjects { get; set; }
    public string Classes { get; set; }
    public string Name { get; set; }
    public List<string> Assign_Content { get; set; }
    public string Creator { get; set; }
    public string isActive { get; set; }
    public string Editor { get; set; }
    public string CreatedDate { get; set; }
    public string LastModifiedDate { get; set; }
}

例外:

Newtonsoft.Json.dll中发生了类型为'Newtonsoft.Json.JsonReaderException'的异常,但未在用户代码中处理

附加信息:解析值后,遇到意外字符:N.路径“ Content [0]”,第1行,位置23。

编辑

感谢kblok我做到了:

JSON = "{\"ID\":123,\"Content\":[\"{\"NewName\":\"fdsgfd\",\"Type\":\"2\"}\"],\"Notes\":[\"\"],\"Type\":2,\"Subjects\":\"Tysk\",\"Classes\":\"3\",\"Name\":\"fdsgfd\",\"Assign_Content\":[\"[{\"Type\":\"text\",\"Text\":\"dfgfgs\"}]\"],\"Creator\":\"example@example.com\",\"isActive\":\"False\",\"Editor\":\"example@example.com\",\"CreatedDate\":\"2017-08-22T00:00:00\",\"LastModifiedDate\":\"2017-08-22T00:00:00\"}";
to
JSON= "{\"ID\":123,\"Content\":[\"{\\\"NewName\\\":\\\"fdsgfd\\\",\\\"Type\\\":\\\"2\\\"}\"],\"Notes\":[\"\"],\"Type\":2,\"Subjects\":\"Tysk\",\"Classes\":\"3\",\"Name\":\"fdsgfd\",\"Assign_Content\":[\"[{\\\"Type\\\":\\\"text\\\",\\\"Text\\\":\\\"dfgfgs\\\"}]\"],\"Creator\":\"example@example.com\",\"isActive\":\"False\",\"Editor\":\"example@example.com\",\"CreatedDate\":\"2017-08-22T00:00:00\",\"LastModifiedDate\":\"2017-08-22T00:00:00\"}";

现在可以使用了!

该字符串的结果:

\"Content\":[\"{\"NewName\":\"fdsgfd\",\"Type\":\"2\"}\"]

是:

"Content":["{"NewName":"fdsgfd","Type":"2"}"]

如您所见,那是无效的JSON。 因此,您需要转义反斜杠以获取有效的JSON。 代替这个:

\"{\"NewName\":\"fdsgfd\",\"Type\":\"2\"}\"

它应该是:

\"{\\\"NewName\\\":\\\"fdsgfd\\\",\\\"Type\\\":\\\"2\\\"}\"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM