ThatBenderGuy ThatBenderGuy - 1 month ago 9
C# Question

C# how to deserialize my json file using Newtonsoft?

Okay so I have looked all over and could not find an answer to how to do this.

Here is my json file

{
"item": {
"icon": "icon.png",
"icon_large": "icon_large.png",
"id": 453,
"type": "misc",
"typeIcon": "icontype.png",
"name": "Item name",
"description": "item description",
"current": {
"trend": "neutral",
"price": 174
},
"today": {
"trend": "positive",
"price": "+2"
},
"premium": "false"
}
}


I have tried this class as a way to deserialize it (I only need the item's name and price from the "current" tree)

public class MyItem
{
public Dictionary<string, Item> item;
}
public class Item
{
public string name;
public Dictionary<string, Current> current;
}
public class Current
{
public string price;
}


And this is being called from my main class

private void buttonAddItemToWatcher_Click(object sender, EventArgs e)
{
string url = "link to json above;
string json = new WebClient().DownloadString(url);

MyItem newItem = new MyItem();

JsonConvert.PopulateObject(json, newItem);

}


but I get this error


An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' >occurred in Newtonsoft.Json.dll

Additional information: Error converting value >"icon.png" to type 'RS_GrandExchangeWatcher.Item'. Path 'item.icon', line 1, position 95.


I am not quite understanding how I should set up my class in order to populate my MyItem class with the json I have provided

Answer

Your C# class does not match your JSON.

Copy your JSON, go to Visual Studio 2015, open a .cs file, in the menu Edit -> Paste Special -> Paste JSON as classes.

How to paste as JSON

And you get corresponding C# classes:

public class MyItem
{
    public Item item { get; set; }
}

public class Item
{
    public string icon { get; set; }
    public string icon_large { get; set; }
    public int id { get; set; }
    public string type { get; set; }
    public string typeIcon { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public Current current { get; set; }
    public Today today { get; set; }
    public string premium { get; set; }
}

public class Current
{
    public string trend { get; set; }
    public int price { get; set; }
}

public class Today
{
    public string trend { get; set; }
    public string price { get; set; }
}