Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I take List<> instead of array in JSON deserialization ?

First of all let me tell you one thing that I am posting this question is just for eagerness and to increase my knowledge. Hope you can clear my doubts !

Now lets come to the point

I got this question from my previous question-answer

Actually the problem is if I use

List<oodleListings> listings;

instead of

oodleListings[] listings;

It works fine !! I can deserialize my json string easily.

Now the problem is why array is not supported while deserializing json ?

What is the actual reason to use List instead of array ?

like image 673
Chintan Avatar asked Feb 10 '12 12:02

Chintan


1 Answers

Your problem is not related with Arrays or Lists. See the example classes below

public class TestClassList
{
    public List<User> users;
}

public class TestClassArray
{
    public User[] users;
}

public class User
{
    public string user;
}

and assume your input string is string json1 = "{ users:[{user:'11'},{user:'22'}] }";

var obj1= ser.Deserialize<TestClassList>(json1);
var obj2 = ser.Deserialize<TestClassArray>(json1);

both deserializations will work..

But if you try to deserialize this string string json2 = "{ users:{user:'11'} }";

var obj3 = ser.Deserialize<TestClassList>(json2);
var obj4 = ser.Deserialize<TestClassArray>(json2);   //<--ERROR  

you will get error in the second line (Althoug first line doesn't give an error, it doesn't return a valid object either).

As a result: The second json string does not contain an array of users, this is why you get No parameterless constructor defined for type of 'User[]'.

like image 96
L.B Avatar answered Oct 26 '22 23:10

L.B