3

我正在从外部 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": [],
            },
        }
    ]
}

我需要"src": "http://myurl.jpg"从此 Json 数组中获取元素。我试过了:

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"];

任何人都可以帮我解决这个问题吗?

4

2 回答 2

7

尝试修复线

JArray media = (JArray)(obj["attachment"]);

JArray media = (JArray)(obj["attachment"]["media"]);
于 2013-11-15T06:08:45.900 回答
1

这就是我处理听起来像你的场景的方式:

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
}
于 2016-04-15T15:31:03.380 回答