skip to Main Content

I am looking a way to get the specific value from complex json without creating the Model class. I am able to read via Newtonsoft but with model and since I have many different json model,is it possible to get the value of content.result.id directly ?
Is ther any way to get it as my json keeps on changing:
Json:

{
    "id": "123",
    "Type": "Test",
    "content": {
        "id": "abcd",
        "testResult": "Failed",
        "field1": {
            "id": "T1",
            "name": "T1 name"
        },
        "filed2": {
            "id": "T2",
            "name": "T2 name "
        },
        "result": {
            "id": "1111",
            "name": "T3 name"
        }
    },
    "createdAt": "2018-10-11T13:18:54.0555456+01:00",
    "updatedAt": "2018-10-11T13:18:54.0555518+01:00",
    "deleted": false,
    "_rid": "AAAA===",
    "_self": "Ab++/",
    "_etag": ""1qw"",
    "_attachments": "attachments/",
    "_ts": 12345
}

Expected outcome: 1111 (from within result)

4

Answers


  1. With Newtonsoft.Json, read the JSON as JObject and get the value with JSON Path.

    using Newtonsoft.Json.Linq;
    
    JObject jObj = JObject.Parse(json);
    string id = jObj.SelectToken("$.content.result.id")
        .ToString();
    

    Reference: Querying JSON with complex JSON Path

    Login or Signup to reply.
  2. if you are using System.Text.Json you can use JsonNode as Follows :

    using System.Text.Json.Nodes;
    
    var jsonObject = JsonNode.Parse(json)!.AsObject();
    
    var id = jsonObject["content"]?["result"]?["id"];
    
    

    or if you are using Newtonsoft you can use JObject as Follows:

    using Newtonsoft.Json.Linq;
        
    var jsonObject = JObject.Parse(json);
    
    var id = jsonObject["content"]?["result"]?["id"]?.ToString();
    
    Login or Signup to reply.
  3. var parsed = JObject.Parse(json);
    var resultId = parsed["content"]["result"]["id"];
    

    You need to add null checking, but that will work.

    Login or Signup to reply.
  4. You can fetch the specific JSON field value without defining a model class by using Newtonsoft’s JObject class

    using Newtonsoft.Json.Linq;
    
    string json = @"{
    // JSON here
    }";
    
    JObject jsonObj = JObject.Parse(json);
    string idValue = (string)jsonObj["content"]["result"]["id"];
    Console.WriteLine("The ID value is: " + idValue);
    

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search