0

I have a json file in the following format:

    {
  "1": {
    "additional text": "Info about ..",
    "description": "you can find info about ... here",
    "link": "https:.."
  },
  "2": {
    "additional text": "Info:",
    "description": "Details about ...",
    "link": "https://..."
  }
}

What I have right now is

dynamic d = JObject.Parse(response.Content.ToString());

With this code, I get the whole json. I don't know how to get the content of 1, and its nested elements.

In the meantime, I also tried

String rootObjects = JsonConvert.DeserializeObject<String>(response.Content.ToString());

but again I have the same problem that I can't get the content of each element.

Filburt
  • 17,626
  • 12
  • 64
  • 115
user1419243
  • 1,655
  • 3
  • 19
  • 33

1 Answers1

3
public class JsonContent {

    [JsonProperty("additional text")]
    public string AdditionalText{get;set;}

    [JsonProperty("description")]
    public string Description{get;set;}

    [JsonProperty("link")]
    public string Link{get;set;}
}


using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
                
public class Program
{
    public static void Main()
    {
        string json = "{\"1\": {\"additional text\": \"Info about ..\", \"description\": \"you can find info about ... here\", \"link\": \"https:..\"}, \"2\": {\"additional text\": \"Info:\", \"description\": \"Details about ...\", \"link\": \"https://...\"}}";
        Dictionary<int, JsonContent> dictionary = JsonConvert.DeserializeObject<Dictionary<int, JsonContent>>(json);
    
        foreach(var item in dictionary) {
            var key = item.Key;
            var content = item.Value;
            Console.WriteLine(String.Format("Key: {0}", key));
            Console.WriteLine(String.Format("AdditionalText: {0}", content.AdditionalText));
            Console.WriteLine(String.Format("Description: {0}", content.Description));
            Console.WriteLine(String.Format("Link: {0}", content.Link));
            Console.WriteLine(string.Empty);
        }
    }
}

You need to install Newtonsoft.Json NuGet package.

Kawsar Hamid
  • 514
  • 3
  • 13