Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get data from Json Object

I am fetching some data from external Webservice and parsing it to json using Newtonsoft.Json.Linq

like this

 JObject o = JObject.Parse(json);
 JArray sizes = (JArray) o["data"];

Now the Sizes looks like this

{
    [
        {
            "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": [],
            },
        }
    ]
}

I need to get "src": "http://myurl.jpg"element from this Json array. I have tried:

foreach (JObject obj in sizes)
{
    JArray media = (JArray)obj["attachment"];
    foreach (JObject obj1 in media)
    {
        var src = obj1["src"];
    }
}

But it's throwing an error:

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.

at this line

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

Can any one give me a hand on this?

like image 567
None Avatar asked May 08 '26 02:05

None


2 Answers

Try fix line

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

to

JArray media = (JArray)(obj["attachment"]["media"]);
like image 93
Vladimir Avatar answered May 09 '26 16:05

Vladimir


This is how I handled a scenario that sounds just like yours:

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
}
like image 38
Anthony Mason Avatar answered May 09 '26 16:05

Anthony Mason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!