[英]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.