我正在尝试使用Json从网站获取数据,我想这是获取数据的最佳方式,因为我可以选择这种类型:
这是一个示例Json字符串:
{
"25":{
"itemName":"Worn Shortsword",
"marketValue":"120000000",
"minBuyout":"0",
"historicalPrice":"0",
"quantity":"0",
"globalMarketValue":"27679191",
"globalMinBuyout":"23303673",
"globalHistoricalPrice":"13771960",
"globalQuantity":"1",
"globalSalePrice":"0"
},
"35":{
"itemName":"Bent Staff",
"marketValue":"10000000",
"minBuyout":"0",
"historicalPrice":"6670500",
"quantity":"0",
"globalMarketValue":"15850430",
"globalMinBuyout":"11381812",
"globalHistoricalPrice":"4527059",
"globalQuantity":"1",
"globalSalePrice":"2061488"
},
"36":{
"itemName":"Worn Mace",
"marketValue":"0",
"minBuyout":"0",
"historicalPrice":"0",
"quantity":"0",
"globalMarketValue":"827553",
"globalMinBuyout":"1024444",
"globalHistoricalPrice":"1903356",
"globalQuantity":"1",
"globalSalePrice":"10000"
}
}
来源:http://api.tradeskillmaster.com/sample_auction_data.json
我尝试使用粘贴作为菜单中的特殊选项创建一个类,但是因为有超过9000个项目,所以它很乱。我也尝试过几个网站来格式化或从Json字符串中创建类,但它只是不起作用,如果我使用一个小样本它添加了很多类,这是我到目前为止的代码:
string url = "http://api.tradeskillmaster.com/sample_auction_data.json";
using (var w = new WebClient()) {
var json_data = string.Empty;
// attempt to download JSON data as a string
try {
json_data = w.DownloadString(url);
} catch (Exception error) {
MessageBox.Show(error.Message);
}
var jObj = JsonConvert.DeserializeObject<Item>(json_data);
}
编辑:哎呀忘了添加问题。
我想获取所有项目的itemName和marketValue,并在dataGridView上显示它们,我只获取Json字符串,但我无法使用数据,尝试反序列化它我认为这是错误的。< / p>
TL; DR:我怎样才能做到这一点,我可以做类似的事情:
dataGridView.Add(jObj[i].itemName, jObj[i].marketValue);
答案 0 :(得分:2)
首先安装Json.Net。
public class Item
{
public string itemName { get; set; }
public string marketValue { get; set; }
public string minBuyout { get; set; }
public string historicalPrice { get; set; }
public string quantity { get; set; }
public string globalMarketValue { get; set; }
public string globalMinBuyout { get; set; }
public string globalHistoricalPrice { get; set; }
public string globalQuantity { get; set; }
public string globalSalePrice { get; set; }
}
var result = JsonConvert.Deserialize<Dictionary<string, Item>>("json string")
foreach (var item in result)
{
// do what you want with result
Debug.WriteLine(item.Key);
}