简体   繁体   中英

Getting error when trying to parse JSON Response - Cannot convert object of type 'System.String' to type ''

Getting error when trying to parse JSON response

try
{
   var result = (new JavaScriptSerializer()).Deserialize<Rootobject>(jsonResponse);
}
catch(Exception ex){}

JSON string

"[{\"ID\":1,\"Code\":null,\"Name\":\"Black\"},{\"ID\":1,\"Code\":null,\"Name\":\"Red\"},{\"ID\":1,\"Code\":\"blx\",\"Name\":\"Blue\"}]"

Screenshot is attached for error details and exact JSON String

在此处输入图片说明

I am generating JSON with following code

   public string JSONTest()
   {
        List<Color> colors = new List<Color>(); 
        colors.Add(new Color() { ID = 1, Name = "Black" }); 
        colors.Add(new Color() { ID = 1, Name = "Red" }); 
        colors.Add(new Color() { ID = 1, Name = "Blue", Code = "blx" }); 

        return JsonConvert.SerializeObject(colors); 
    }

Try this

var result = (new JavaScriptSerializer()).Deserialize<List<Class1>>(jsonResponse);

your result will be a list of Class1

在此处输入图片说明

Hey try using below:

 Class1 obj=new Class1();
 obj=serializer.Deserialize<Class1>(jsonResponse);

JSON string deserialization needs the Root Key to complete the deserialization process

In your case , this JSON does not know which object to deserialize

You must be show to deserialize class in JSON string..

 public class Rootobject
 {         
    public Class1[] Property1 { get; set; }
 }


 public class Class1
 {
    public int ID { get; set; }

    public string Code { get; set; }

    public string Name { get; set; }
 }



     string jsonResponse = "{ \"Property1\" :  [{\"ID\":1,\"Code\":null,\"Name\":\"Black\"},{\"ID\":1,\"Code\":null,\"Name\":\"Red\"},{\"ID\":1,\"Code\":\"blx\",\"Name\":\"Blue\"}] }";

     var result = (new JavaScriptSerializer()).Deserialize<Rootobject>(jsonResponse);

Generate JSON string with Root Key

    public string JSONTest()
    {

        List<Class1> colors = new List<Class1>();
        colors.Add(new Class1() { ID = 1, Name = "Black" });
        colors.Add(new Class1() { ID = 1, Name = "Red" });
        colors.Add(new Class1() { ID = 1, Name = "Blue", Code = "blx" });

        return JsonConvert.SerializeObject(new Rootobject { Property1 = colors.ToArray() });
    }

Alternatifly,

DeserializeObject method can be deserialized on object directly. if you use it like this you will not need Root Key but return value will be an object..

 string jsonResponse = "[{\"ID\":1,\"Code\":null,\"Name\":\"Black\"},{\"ID\":1,\"Code\":null,\"Name\":\"Red\"},{\"ID\":1,\"Code\":\"blx\",\"Name\":\"Blue\"}]";
                object[] result = (object[])(new JavaScriptSerializer()).DeserializeObject(jsonResponse);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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