Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON object into a C# list

I'm trying to deserialize a given JSON file in C# using a tutorial by Bill Reiss. For XML data in a non-list this method works pretty well, though I would like to deserialize a JSON file with the following structure:

public class Data
{
    public string Att1 { get; set; }
    public string Att2 { get; set; }
    public string Att3 { get; set; }
    public string Att4 { get; set; }
}

public class RootObject
{

public List<Data> Listname { get; set; }
}

My problem is with using JSON.Net's ability to create / put data into lists, and then displaying the list on an XAML page. My idea so far (which is not working):

var resp = await client.DoRequestJsonAsync<DATACLASS>("URL");
string t = resp.ToString();
var _result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DATACLASS>>(t);
XAMLELEMENT.ItemsSource = _result;
like image 754
user2282587 Avatar asked Apr 15 '13 16:04

user2282587


1 Answers

So I think you're probably trying to deserialize to the wrong type. If you serialized it to RootObject and try to deserialize to List it's going to fail.

See this example code

public void TestMethod1()
    {
        var items = new List<Item>
                        {
                            new Item { Att1 = "ABC", Att2 = "123" }, 
                            new Item { Att1 = "EFG", Att2 = "456" }, 
                            new Item { Att1 = "HIJ", Att2 = "789" }
                        };
        var root = new Root() { Items = items };
        var itemsSerialized = JsonConvert.SerializeObject(items);
        var rootSerialized = JsonConvert.SerializeObject(root);

        //This works
        var deserializedItemsFromItems = JsonConvert.DeserializeObject<List<Item>>(itemsSerialized); 

        //This works
        var deserializedRootFromRoot = JsonConvert.DeserializeObject<Root>(rootSerialized); 

        //This will fail.  YOu serialized it as root and tried to deserialize as List<Item>
        var deserializedItemsFromRoot = JsonConvert.DeserializeObject<List<Item>>(rootSerialized);

        //This will fail also for the same reason 
        var deserializedRootFromItems = JsonConvert.DeserializeObject<Root>(itemsSerialized);
    }

class Root
{
    public IEnumerable<Item> Items { get; set; } 
}

class Item
{
    public string Att1 { get; set; }
    public string Att2 { get; set; }
}

Edit: Added complete code.

like image 164
cgotberg Avatar answered Oct 06 '22 03:10

cgotberg