Reputation: 99
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"
}
]
Upvotes: 6
Views: 25092
Reputation: 1500815
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
}
}
Upvotes: 11
Reputation: 32713
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);
Upvotes: 6