Zero
Zero

Reputation: 118

Deserializing Json Array to C# List<T>

I'm new at Json Serialization and Deserialization,

I have

class TestClass
{

    public string Name{get;set;}
    public string Age{get;set;}
    public string Height{get;set;}

}

and have the following serialization function

public void SerializeData()
{

    string jsonData = "{
           {"Name" : "Zeus","Age" : "1825","Height" : "900"},
           {"Name" : "Hera","Age" : "1805","Height" : "200"}
     }";

    var resultList = new List<TestClass>();
    var ser = new JavaScriptSerializer();

    resultList= serializer.Deserialize(jsonData , TestClass)

}

but it doesn't work! keeps throwing "Argument Exception"

Any Help Please?

Upvotes: 0

Views: 2387

Answers (2)

Felice Pollano
Felice Pollano

Reputation: 33252

this does not represent an array:

string jsonData = "{
           {"Name" : "Zeus","Age" : "1825","Height" : "900"},
           {"Name" : "Hera","Age" : "1805","Height" : "200"}
     }";

In order to have an array you should have:

string jsonData = "[
           {"Name" : "Zeus","Age" : "1825","Height" : "900"},
           {"Name" : "Hera","Age" : "1805","Height" : "200"}
     ]";

Upvotes: 1

Stuart
Stuart

Reputation: 66882

It looks like your JSON might be incorrect.

A List maps more closely to a JSON array - like:

 [
       {"Name" : "Zeus","Age" : "1825","Height" : "900"},
       {"Name" : "Hera","Age" : "1805","Height" : "200"}
 ]

If you want to use outer curly braces {} then you can serialize to/from a Dictionary<string, TestClass> using JSON like:

 {
       "Zeus" : {"Name" : "Zeus","Age" : "1825","Height" : "900"},
       "Hera" : {"Name" : "Hera","Age" : "1805","Height" : "200"}
 ]

Upvotes: 3

Related Questions