【问题标题】:Make dynamic dictionary from json file从 json 文件制作动态字典
【发布时间】:2017-09-17 19:35:57
【问题描述】:

我有这样的 json 文件:

{
    "fields": {
        "customfield_10008": {
              "value": "c1"
        },
        "customfield_10009": {
              "value": "c2"
       }
            ...
    }
}

我想在 c# 中创建字典,例如:

key:    value
"customfield_10008":"c1"
"customfield_10009":"c2"

我怎样才能做到这一点?我是这样加载json的,

dynamic json = JsonConvert.DeserializeObject(File.ReadAllText("data.json");

不知道如何像上面那样创建字典

【问题讨论】:

    标签: c# json linq dictionary


    【解决方案1】:

    一点点 linq 技巧可以帮助你

    var dict = JObject.Parse(File.ReadAllText("data.json"))["fields"]
               .Cast<JProperty>()
               .ToDictionary(x => x.Name, x => (string)x.Value["value"]);
    

    【讨论】:

      【解决方案2】:

      通过价值来收集它们:

      var result = new Dictionary<string, string>();
      foreach (var field in obj.fields)
      {
          result.Add(field.Name, Convert.ToString(field.Value.value));
      }
      

      【讨论】:

        【解决方案3】:

        如果你有编译时没有类型的json,你可以在那个时候使用dynamic类型。

        我会使用 dynamic 类型解析上面的 json 并生成带有解析值的 dictionary

        var dicValues = new Dictionary<string,string>(); // this dictionary contains key value pair result
        dynamic res = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText("data.json");
        dynamic availableFields = res["fields"];
        if (availableFields != null)
        {
            foreach (var field in availableFields)
                dicValues.Add(field.Name, field.Value["value"].Value);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-17
          • 2021-10-26
          • 1970-01-01
          • 2016-05-23
          • 2017-04-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多