Tayfur Yılmaz
Tayfur Yılmaz

Reputation: 21

How to check specified children name included in Parent on JArray with Linq query

I have as same as following Json data

"widget": {
        "debug": "on",
        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "width": 500,
            "height": 500
        },
        "image": { 
            "src": "Images/Sun.png",
            "name": "sun1",
            "hOffset": 250,
            "vOffset": 250,
            "alignment": "center"
        },
        "text": {
            "data": "Click Here",
            "size": 36,
            "style": "bold",
            "name": "text1",
            "hOffset": 250,
            "vOffset": 100,
            "alignment": "center",
            "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
        }

And How can I check widget Parent node include image children node with linq ? I have if-else condition if widget parent included specified children node .

if Parent have children property, I gonna feed my db with property data and run if code block with return true.

My tried query which children does match parent node.

if(!((from x in widget[i].Children() where x.Contains("image") select x) is Nullable)) 
     something else..
else
    something else..

if Parent haven't any specified children which one I give a parameter with children value, run else block state with return false.

My tried query which children does not match parent node.

  if(!((from x in widget[i].Children() where x.Contains("link") select x) is Nullable)) 
           something else..
        else
            something else..

But I didn't do when Parent haven't specified children node and run else block.. Best Regards .

Upvotes: 0

Views: 989

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236278

You don't need query here - just access tokens by key:

JObject obj = JObject.Parse(json);
bool imageExists = obj["widget"]["image"] != null;

Assume you have follwing JSON:

{
   "widget": {
        "debug": "on",
        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "width": 500,
            "height": 500
        },
        "image": { 
            "src": "Images/Sun.png",
            "name": "sun1",
            "hOffset": 250,
            "vOffset": 250,
            "alignment": "center"
        },
        "text": {
            "data": "Click Here",
            "size": 36,
            "style": "bold",
            "name": "text1",
            "hOffset": 250,
            "vOffset": 100,
            "alignment": "center",
            "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
        }
    }
}

Upvotes: 1

Related Questions