简体   繁体   中英

Reading JSON file inside C# using JSON.net

I've retrieved a pretty big JSON file from a Steam web api. It has multiple objects and tokens. I'm wondering what the best way to go about reading this file inside C#.

There's an example of the sort of data this program will have to decode here: http://pastebin.com/nNw7usZW

The only data i'm interested is the items "icon_url_large", "market_name" and "type" inside the object "rgDescriptions". So far i've tried using

WebClient c = new WebClient();
var json = c.DownloadString(url);
JObject o = JObject.Parse(json);

Not really sure where to progress from here, or how to use the parser results. In the end I'm wanting to put the list of "market_name" values into a dropdownbox.

Thanks

you can use the Newtonsoft.Json.dll , In that you have to create a class and declare a properties in it so you can DeserializeObject and use only those property which you want.

like

public class MyClass
        {

            public int First { get; set; }
            public string Name { get; set; }

        }

 var abc = JsonConvert.DeserializeObject<MyClass>(jsonData);

You can either create a class matching your json representation and deserialize it using JsonConvert.DeserializeObject method, or keep your JObject. JObject are dynamic objects, therefore your into dynamic then explore the object tree easily.

Working with JsonConvert.DeserializeObject

class MyDataObject
{
   public string Data1{get;set;}
   [...]
}

string jsonText = ...;
var dataObject = JsonConvert.DeserializeObject<MyDataObject>(jsonText);
var myData = dataObject.Data1;

Working with JObject

WebClient c = new WebClient();
var json = c.DownloadString(url);
dynamic o = JObject.Parse(json); 

var myData = o.Data1; 

The JObject option is simplier, but you won't benefit from static typing using it. Enjoy! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM