Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type is not supported for deserialization of an array

Tags:

json

arrays

c#

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"
 }
]
like image 948
user3478897 Avatar asked Sep 03 '14 21:09

user3478897


2 Answers

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
    }
}
like image 118
Jon Skeet Avatar answered Oct 17 '22 02:10

Jon Skeet


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);
like image 37
Donal Avatar answered Oct 17 '22 00:10

Donal