【问题标题】:list to json object using json.net使用 json.net 列出 json 对象
【发布时间】:2012-01-08 14:38:20
【问题描述】:

我正在使用 json.net 将货币汇率转换为 json。

C# 实体有一个 Name 和一个 Value,其中 Name 是 USD、GBP 等等,Value 是货币汇率。

我不知道不同货币的索引,所以在 javascript 中我想通过说 var a = obj["USD"]; insead 循环遍历数组并找到 array[i].name == "USD" 来获取货币。 JsonConvert.SerializeObject(currencyList); 的默认输出为:

[
    {"name": "one",   "pId": "foo1", "cId": "bar1"},
    {"name": "two",   "pId": "foo2", "cId": "bar2"},
    {"name": "three", "pId": "foo3", "cId": "bar3"}
]

我想要类似的东西:

{
    "one":   {"pId": "foo1", "cId": "bar1"},
    "two":   {"pId": "foo2", "cId": "bar2"},
    "three": {"pId": "foo3", "cId": "bar3"}
}

这可以通过 json.net 实现吗,还是我需要编写自己的解析器?

【问题讨论】:

    标签: c# javascript json.net


    【解决方案1】:

    你必须创建一个字典:

    Dictionary<String, DataType> dictionary = list.ToDictionary(d => d.name);
    

    DataType 替换为您的实体类型。

    然后,您可以使用 json 序列化字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 2011-05-30
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多