我正在从外部Web服务获取一些数据,并使用Newtonsoft.Json.Linq将其解析为json。
喜欢这个
JObject o = JObject.Parse(json);
JArray sizes = (JArray) o["data"];
现在Sizes
看起来像这样
{
[
{
"post_id": "13334556777742_6456",
"message": "messagecomes her",
"attachment": {
"media": [
{
"href": "http://onurl.html",
"alt": "",
"type": "link",
"src": "http://myurl.jpg"
}
],
"name": "come to my name",
"href": "http://mydeeplink.html",
"description": "",
"properties": [],
},
}
]
}
我需要从这个 Json 数组中获取"src": "http://myurl.jpg"
元素。我试过:
foreach (JObject obj in sizes)
{
JArray media = (JArray)obj["attachment"];
foreach (JObject obj1 in media)
{
var src = obj1["src"];
}
}
但它抛出了一个错误:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
在这一行
JArray media = (JArray)obj["attachment"];
谁能帮我一把?
尝试修复行
JArray media = (JArray)(obj["attachment"]);
自
JArray media = (JArray)(obj["attachment"]["media"]);
这就是我处理听起来像你的场景的方式:
public static IList<Entity> DeserializeJson(JToken inputObject)
{
IList<Entity> deserializedObject = new List<Entity>();
foreach (JToken iListValue in (JArray)inputObject["root"])
{
Entity entity = new Entity();
entity.DeserializeJson(iListValue);
deserializedObject.Add(entity);
}
return deserializedObject;
}
public virtual void DeserializeJson(JToken inputObject)
{
if (inputObject == null || inputObject.Type == JTokenType.Null)
{
return;
}
inputObject = inputObject["entity"];
JToken assertions = inputObject["assertions"];
if (assertionsValue != null && assertionsValue.Type != JTokenType.Null)
{
Assertions assertions = new Assertions();
assertions.DeserializeJson(assertionsValue);
this.Assertions = assertions;
}
// Continue Parsing
}