如何在C#中解析此jsonobject

时间:2020-09-03 11:02:16

标签: c# json

我有一个json文件,格式如下:

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

我现在拥有的是

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

使用此代码,我得到了整个json。我不知道如何获取1的内容及其嵌套元素。

与此同时,我也尝试过

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

但是我仍然遇到同样的问题,我无法获取每个元素的内容。

1 个答案:

答案 0 :(得分:2)

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);
        }
    }
}

您需要安装Newtonsoft.Json NuGet软件包。