Json string deserialized to array list of objects

16,067

Solution 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);

Solution 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>.

Share:
16,067
user1553087
Author by

user1553087

Updated on June 05, 2022

Comments

  • user1553087
    user1553087 almost 2 years

    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; }
    }
    
  • user1553087
    user1553087 over 11 years
    As you suggested I did this: string strResult = serializer.Deserialize<String>(str); List<RawAnswer> LAsnwers = serializer.Deserialize<List<RawAnswer>>(strResult); I got LAnswers values = null (QuestionID=null and Answer=null)
  • user1553087
    user1553087 over 11 years
    It Works! THANK YOU so much! Basically the properties of my object must be the same of the fields in the json string.