Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# access JSON content by ID

Tags:

json

c#

So I need to parse a JSON string from my C# project. I get my JSON as a response from a method call and the json looks like this:

{
    "10": {
        "entity_id": "10",
        "attribute_set_id": "4",
        "type_id": "simple",
        "sku": "convertor-touchscreen",
        "name": "Convertor touchscreen",
        "meta_title": null,
        "meta_description": null,
        "url_key": "convertor-touchscreen",
        "custom_design": null,
        "page_layout": null,
        "options_container": "container1",
        "country_of_manufacture": null,
        "msrp_enabled": "2",
        "msrp_display_actual_price_type": "4",
        "gift_message_available": null,
        "creareseo_discontinued": null,
        "creareseo_discontinued_product": null,
        "description": "Convertor touchscreen",
        "short_description": "Convertor touchscreen",
        "meta_keyword": null,
        "custom_layout_update": null,
        "price": "421.0000",
        "special_price": "380.0000",
        "weight": "0.1500",
        "msrp": null,
        "special_from_date": "2015-11-24 00:00:00",
        "special_to_date": "2015-11-26 00:00:00",
        "news_from_date": null,
        "news_to_date": null,
        "custom_design_from": null,
        "custom_design_to": null,
        "status": "1",
        "visibility": "4",
        "tax_class_id": "2",
        "featured": "1"
    }
}

So I need to access members like "entity_id","name" and so on... so I tried

using Newtonsoft.Json.Linq;
...
// output is the above JSON string
var jo = JObject.Parse(output);
var id = jo[0]["entity_id"].ToString();

But obviously it's not a good way to do it. Also, I do not have control over the first part

{
    "10": {

So I cannot do

var id = jo["10"]["entity_id"].ToString();

because I do not know what the value "10" will be in my next JSON string. So how can I get the element value by an Id or something?

like image 439
user1137313 Avatar asked Nov 28 '25 14:11

user1137313


1 Answers

If you don't know the value of 10 in advance it's obvious that you cannot access its contents using this key (in your example that would be the key to access the other properties). If this object will always have 1 top level property then your code is just fine:

var jo = JObject.Parse(output);
var id = jo[0]["entity_id"].ToString();

with some added defensive checks that the jo array has at least one property before trying to access it.

On the other hand if the key is inside some property of the entity that you know about it, then feel free to loop over all the top level properties of the jo variable inspecting the sub-properties for the values of the key you know about until you find the desired record.

like image 173
Darin Dimitrov Avatar answered Dec 01 '25 05:12

Darin Dimitrov