user3064309 user3064309 - 10 days ago 6
JSON Question

Get json properties by attributes c#

I have a Json Object like the one below.

"log": {
"Response": [
{
"@type": "Authentication",
"Status": "True",
"Token": "cc622e9c-0d56-4774-8d79-543c525471b4"
},
{
"@type": "GetApplication",
"AppId": 100,
"Available": "True"
}]}


I need to access the appId property. I have tried the below code which gives the null reference error. Please help me figure out the mistake.

dynamic JsonText = JObject.Parse(result);
string AppId= JsonText ["log"]["Response @type='GetApplication'"]["AppId"].Tostring();

Answer

Here dotNetFiddle

          string json = @"{
    ""log"": {

        ""Response"": [{
            ""@type"": ""Authentication"",
            ""Status"": ""True"",
            ""Token"": ""cc622e9c-0d56-4774-8d79-543c525471b4""

        }, {
            ""@type"": ""GetApplication"",
            ""AppId"": 100,
            ""Available"": ""True""
        }]
    }
}";

            JObject result = JObject.Parse(json);

            foreach(var item in result["log"]["Response"])
            {
                Console.WriteLine(item["@type"]);
                Console.WriteLine(item["AppId"]);
            }

You don't need to use dynamic, use JObject and after that loop in the Responses and take the @type