【问题标题】:How to parse json into a dictionary<string, SoilStat> using FastJSON如何使用 FastJSON 将 json 解析为字典<string, SoilStat>
【发布时间】:2015-12-19 05:11:47
【问题描述】:

如何使用FastJSON 将 json 转换为字典。 string(key) 是土壤的名称。

非常感谢!

    "Soil": [
        {
            "name": "Pebbiland",
            "retentionrate": 1,
            "cost": 100
        },
        {
            "name": "Sandiland",
            "retentionrate": 4,
            "cost": 500
        },
        {
            "name": "Spongiland",
            "retentionrate": 8,
            "cost": 1000
        }


public class SoilStat
{
    public int retentionRate;
    public int cost;
}


Dictionary<string, SoilStat> _soilList = new Dictionary<string, SoilStat>();

【问题讨论】:

  • 抱歉,在显示的 json 中,“name”只是一个成员 od SoilStat,而不是一个键。它可以作为 SoilStat 列表工作(无论如何在 JSON、NET 中)

标签: c# json fastjson


【解决方案1】:

首先,您的 JSON 不完整。我假设您实际上是这个意思:

{
    "Soil": 
    [
        {
            "name": "Pebbiland",
            "retentionrate": 1,
            "cost": 100
        },
        {
            "name": "Sandiland",
            "retentionrate": 4,
            "cost": 500
        },
        {
            "name": "Spongiland",
            "retentionrate": 8,
            "cost": 1000
        }
    ]
}

您可以使用以下代码在fastJSON中解析上述JSON:

public class Root
{
    public List<SoilStat> Soil;
}

public class SoilStat
{
    public string name;
    public int retentionRate;
    public int cost;
}

Root root = fastJSON.JSON.ToObject<Root>(jsonString);

如果你需要它作为字典,你可以像这样转换它(假设所有的名字都是唯一的):

Dictionary<string, SoilStat> _soilList = root.Soil.ToDictionary(o => o.name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多