简体   繁体   English

使用JSON.net在C#中读取JSON文件

[英]Reading JSON file inside C# using JSON.net

I've retrieved a pretty big JSON file from a Steam web api. 我已经从Steam网络API检索了一个很大的JSON文件。 It has multiple objects and tokens. 它具有多个对象和令牌。 I'm wondering what the best way to go about reading this file inside C#. 我想知道在C#中读取此文件的最佳方法是什么。

There's an example of the sort of data this program will have to decode here: http://pastebin.com/nNw7usZW 这里有一个程序必须解码的数据示例: http : //pastebin.com/nNw7usZW

The only data i'm interested is the items "icon_url_large", "market_name" and "type" inside the object "rgDescriptions". 我唯一感兴趣的数据是对象“ rgDescriptions”中的“ icon_url_large”,“ market_name”和“ type”项。 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. 最后,我想将“ market_name”值列表放入下拉框。

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. 您可以使用Newtonsoft.Json.dll ,因为您必须创建一个类并在其中声明一个属性,以便可以DeserializeObject并仅使用所需的那些属性。

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. 您可以创建一个与json表示形式匹配的类,然后使用JsonConvert.DeserializeObject方法对其进行反序列化,也可以保留JObject。 JObject are dynamic objects, therefore your into dynamic then explore the object tree easily. JObject是动态对象,因此您进入动态然后轻松地浏览对象树。

Working with JsonConvert.DeserializeObject 使用JsonConvert.DeserializeObject

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

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

Working with JObject 使用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. JObject选项更简单,但是您不能从使用它的静态类型中受益。 Enjoy! 请享用! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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