2

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; }
}
aKzenT
  • 7,775
  • 2
  • 36
  • 65
user1553087
  • 47
  • 1
  • 1
  • 7
  • 1
    I edited your question to remove the double escaping, because I thought it was a pasting error here. Now after the answer from Stripling Warrior I'm not sure if this is really the string you get or not... Please advice and edit the question again accordingly. Thanks! – aKzenT Oct 02 '12 at 21:19
  • The original string was the correct one from the client side. I fixed it back – user1553087 Oct 02 '12 at 21:25

2 Answers2

9

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);
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 1
    It Works! THANK YOU so much! Basically the properties of my object must be the same of the fields in the json string. – user1553087 Oct 02 '12 at 21:31
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>.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • As you suggested I did this: string strResult = serializer.Deserialize(str); List LAsnwers = serializer.Deserialize>(strResult); I got LAnswers values = null (QuestionID=null and Answer=null) – user1553087 Oct 02 '12 at 21:21