[英]Deserializing a JSON file using C#
我正在创建一个Steam APP(针对Steam平台),并且需要反序列化JSON文件。
{
"response": {
"success": 1,
"current_time": 1401302092,
"raw_usd_value": 0.245,
"usd_currency": "metal",
"usd_currency_index": 5002,
"items": {
"A Brush with Death": {
"defindex": [
30186
],
"prices": {
"6": {
"Tradable": {
"Craftable": [
{
"currency": "metal",
"value": 4,
"last_update": 1398990171,
"difference": 0.17
}
]
}
}
}
},
...
我只需要获取Defindex和价值。 已经反序列化了一些简单的JSON文件,但是我认为这更复杂。
对于那些想知道的人,我正在使用BackpackTF的API ...
使用NewtonSoft.Json然后,您可以按以下方式使用它来获取数据。
dynamic json = JsonConvert.DeserializeObject(<yourstring>);
string currency = json.response.usd_currency; // "metal"
通常,您要做的是确保您具有有效的JSON(为此使用JSON LINT ),然后使用Json2CSharp获取C#类定义,然后您将执行以下操作:
MyClass myobject=JsonConvert.DeserializeObject<MyClass>(json);
(我们假设MyClass基于您从Json2CSharp获得的内容)
然后,您可以通过传统的C#点表示法访问所需的值。
使用nuget包调用程序Newtonsoft.Json.5.0.8。 它在nuget存储库上。
这行代码将把您的json作为字符串,并将其变成其根对象。
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
您提供的Json有点瑕疵,但是我猜想您要查找的c#对象的结构接近此:
public class Craftable
{
public string currency { get; set; }
public int value { get; set; }
public int last_update { get; set; }
public double difference { get; set; }
}
public class Tradable
{
public List<Craftable> Craftable { get; set; }
}
public class Prices
{
public Tradable Tradable{ get; set; }
}
public class Items
{
public List<int> defindex { get; set; }
public Prices prices { get; set; }
}
public class Response
{
public int success { get; set; }
public int current_time { get; set; }
public double raw_usd_value { get; set; }
public string usd_currency { get; set; }
public int usd_currency_index { get; set; }
public Items items { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.