我知道这听起来很基本,但围绕这个问题的所有答案都是愚蠢的大而笨重的代码,不允许我需要的功能。 我需要解析这个 JSON 数组。
[
{
"label":"Cow (1)",
"value":3309
},
{
"label":"Cow (1)",
"value":14998
},
{
"label":"Cow (4)",
"value":20969
},
{
"label":"Cow (4)",
"value":20970
},
{
"label":"Cow (4)",
"value":20971
},
{
"label":"Cowardly Bandit",
"value":1886
},
{
"label":"Cow calf (1)",
"value":2310
},
{
"label":"Coward in armour (82)",
"value":5097
},
{
"label":"Coward with bow (105)",
"value":6049
},
{
"label":"Cow calf (1)",
"value":20979
},
{
"label":"Undead cow (4)",
"value":1691
},
{
"label":"Plague cow",
"value":1998
},
{
"label":"Plague cow",
"value":1999
},
{
"label":"Unicow (57)",
"value":5603
},
{
"label":"Zombie cow (1)",
"value":18597
},
{
"label":"Zombie cow (1)",
"value":20928
},
{
"label":"Super Cow (5)",
"value":21497
},
{
"label":"Dairy cow",
"value":22418
},
{
"label":"Armoured cow thing (62)",
"value":5986
},
{
"label":"Armoured cow thing (62)",
"value":6048
}
]
当我尝试访问数组内的数据点时,它会返回 null,代码:
Stream stream = client.OpenRead("http://services.runescape.com/m=itemdb_rs/bestiary/beastSearch.json?term=" + Input);
StreamReader reader = new StreamReader(stream);
jObject = JObject.Parse(reader.ReadToEnd());
stream.Close();
//put items into list view
// i is the number where the json object is in the array
var lvi = new ListViewItem(new string[] { (string)jObject[i]["label"], (string)jObject[i]["value"] });
我不想使用类
在代码中发现错误。相反:
JObject.Parse(reader.ReadToEnd());
写(JObject -> JArray):
string text = reader.ReadToEnd();
var jObject = JArray.Parse(text);
同样,当在 2 行中执行写入操作时,您将看到错误所在:从流中读取或序列化。
不想使用类很奇怪,但并非不可能。
var json = reader.ReadToEnd();
var objects = JsonConvert.DeserializeObject<dynamic[]>(json);
var lvi = new ListViewItem(new string[] { (string)objects[i].label, (string)objects[i].value });
试试我对这个问题的回答:
public IEnumerable<MeItem> DeserializeListFromJson(string jsonArray)
{
return JsonConverter.DeserializeObject<List<JObject>>(jsonArray).Select( obj => DeserializeFromJson(obj) );
}
public MeItem DeserializeFromJson(string jsonString)
{
return JsonConvert.DeserializeObject<MeItem>(jsonString);
}
您可以在我对此问题和此问题的回答中找到必要的详细信息
编辑:
如果你不想使用类,那么你可以DeserializeFromJson()
方法修改为这样的东西:
public KeyValuePair<string, string> DeserializeFromJson(JObject obj)
{
return new KeyValuePair<string, string>(obj.SelectToken("label").Value<string>(), obj.SelectToken("value").Value<string>());
}
这将需要DeserializeListFromJson()
方法修改为:
public IEnumerable<KeyValuePair<string,string>> DeserializeListFromJson(string jsonArray)
{
return JsonConverter.DeserializeObject<List<JObject>>(jsonArray).Select( obj => DeserializeFromJson(obj) );
}
与您的案例一起使用 :
Stream stream = client.OpenRead("http://services.runescape.com/m=itemdb_rs/bestiary/beastSearch.json?term=" + Input);
ListViewItem item = null;
using (StreamReader reader = new StreamReader(stream))
{
KeyValuePair<string, string> selected = DeserializeListFromJson(reader.ReadToEnd()).ElementAt(i);
item = new ListViewItem(new string[] { selected.Key, selected.Value });
}