How to get specific data from JSON using C#?

I’m trying to read from a JSON file and print to the console. I’m using the Newtonsoft.Json package to do this.

When I run my code, nothing is displayed. I’m not entirely sure why this is. When I write to the console to display the entire JSON, its fine. But when I try to access specific data, it doesn’t. Why is this?

An example of how I am trying to print to the console:

Stream: Branch Data
Tag: Tag Data

I can’t seem to get the data to print after "Stream:", etc. Its just empty.

Here is my JSON:

  {
  "Data":
  {
    "Branch": "main",
    "BuildDateStamp": "Sat Jul 16 2022",
    "BuildTimeStamp": "08:38:36 PM CST",
    "RequestedP4ChangeNum": "8138336",
    "Tag": "no_tag"
  }
}

Here is my Code:

public static async Task ShowBuildManifest()
        {            
            // Path to JSON File
            string path = "build_manifest.json";

            // This reads the entire JSON file to a string variable (json)
            string json = File.ReadAllText(path);

            // This will deserialize the JSON string into a JObject (Using the Newtonsoft.Json package)
            //var data = JsonConvert.DeserializeObject(json);
            JObject obj = JObject.Parse(json);

            // access specific data in JObject.
            string branch = (string)obj["Data.Branch"];
            string buildDate = (string)obj["BuildDateStamp"];
            string buildTime = (string)obj["BuildTimeStamp"];
            string change = (string)obj["RequestedP4ChangeNum"];
            string tag = (string)obj["Tag"];

            // print data
            Console.WriteLine($"Stream: {branch}");
            Console.WriteLine($"Change: {change}");
            Console.WriteLine($"Build Date: {buildDate}");
            Console.WriteLine($"Build Time: {buildTime}");
            Console.WriteLine($"Tag: {tag}");
        }

>Solution :

you forgot about Data property that wraps all your data. The easiest way to fix would be

            JObject data = (JObject) JObject.Parse(json)["Data"];

             string branch = (string)data["Branch"];
            string buildDate = (string)data["BuildDateStamp"];
            string buildTime = (string)data["BuildTimeStamp"];

you can still use Data but the syntax will be more complicated

    JObject jObj = JObject.Parse(json);
    
    string branch = (string)jObj["Data"]["Branch"];

    //or using dot
    branch = (string)jObj.SelectToken("Data.Branch");
    
    //or
    branch = jObj.SelectToken("Data.Branch").Value<string>();

    //or credits to @PowerMouse
    branch = jObj.SelectToken("Data").Value<string>("Branch");

Leave a Reply