简体   繁体   English

如何将json解析为字典 <string, SoilStat> 使用FastJSON

[英]How to parse json into a dictionary<string, SoilStat> using FastJSON

How to convert json into a dictionary using FastJSON . 如何使用FastJSON将json转换为字典。 The string(key) is the name of the soil. 字符串(键)是土壤的名称。

Thanks alot! 非常感谢!

    "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>();

First of all, your JSON is incomplete. 首先,您的JSON不完整。 I'm assuming you actually meant this: 我假设您实际上是这个意思:

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

You can parse the above JSON in fastJSON using the following code: 您可以使用以下代码在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);

If you need it as a dictionary you can convert it like this (assuming all the names are unique): 如果您需要将它用作字典,则可以按以下方式进行转换(假设所有名称都是唯一的):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM