Type is not supported for deserialization of an array

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I'm trying to dezerialize an array but I keep running into an error.

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); Profiles thingy = jsonSerializer.Deserialize<Profiles>(fileContents); 

This is the code that gives me the error:

Type is not supported for deserialization of an array.

This is how my JSON looks:

[  {   "Number": 123,   "Name": "ABC",   "ID": 123,   "Address": "ABC"  } ] 

回答1:

You just need to deserialize it to a collection of some sort - e.g. an array. After all, your JSON does represent an array, not a single item. Short but complete example:

using System; using System.IO; using System.Web.Script.Serialization;  public class Person {     public string Name { get; set; }     public string ID { get; set; }     public string Address { get; set; }     public int Number { get; set; } }  class Test {     static void Main()     {         var serializer = new JavaScriptSerializer();         var json = File.ReadAllText("test.json");         var people = serializer.Deserialize<Person[]>(json);         Console.WriteLine(people[0].Name); // ABC     } } 


回答2:

The JSON is a list. The square brackets in JSON indicate an array or list of objects. So you need to tell it to return a list of objects:

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); var profiles = jsonSerializer.Deserialize<List<Profiles>>(fileContents); 


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