0

如何使用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>();
4

1 回答 1

0

首先,您的 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);
于 2015-12-19T18:11:55.170 回答