Json string deserialized to array list of objects

旧城冷巷雨未停 提交于 2019-12-21 06:43:15

问题


Please help! Getting this error on Deserializing:

Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List'

JSON string from client:

"\"[{\\"id\\":\\"18_0_2_0\\",\\"ans\\":\\"You can enter free text in place of *\\"},{\\"id\\":\\"23_1_3_1\\",\\"ans\\":\\"The refresh button\\"},{\\"id\\":\\"11_2_1_2\\",\\"ans\\":\\"False\\"}]\""

Edit: Unescaped (see comments):

[{"id":"18_0_2_0","ans":"You can enter free text in place of *"},{"id":"11_2_1_2","ans":"False"}]

JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RawAnswer> ListAnswers = serializer.Deserialize<List<RawAnswer>>(str);
 [Serializable]
public class RawAnswer
{       
    public string QuestionID { get; set; }
    public string Answer { get; set; }

    public RawAnswer() { }

}

public class AnswerList
{
    public List<RawAnswer> RawAnswer { get; set; }
}

回答1:


Your original json string(before aKzenT's edit) was double escaped and I used var str2 = Regex.Unescape(str); to get the actual string .

public class RawAnswer
{
     public string id { get; set; }
     public string ans { get; set; }

}

And no need for AnswerList

Now your code can work

JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RawAnswer> ListAnswers = serializer.Deserialize<List<RawAnswer>>(str);



回答2:


The JSON string you receive from the client is itself a string containing the actual JSON string you're looking for. Either fix the client to send you a correct string, or first deserialize this result into a String, and then deserialize that into a List<RawAnswer>.



来源:https://stackoverflow.com/questions/12698365/json-string-deserialized-to-array-list-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!