将JSON文件序列化为类和字典

时间:2018-10-11 05:04:03

标签: c# json dictionary serialization json.net

我的类结构是固定的,但是对象变量(属性)不是固定的。这些数据是可配置的。我正在用字典创建一个类,但无法正常工作。

例如。

{
"datamapItems": [
      {
        "paramName": "VE8321C",
        "datamapKey": {
          "module": 1,
          "id": 1391
        },
        "min": "0",
        "max": "40",
        "default": 222,
        "rateHz": 0,
        "timeoutMs": 0,
        "dataType": "uint16"
      }
   ]
}

对于这些JSON结构,我们创建了以下类结构。但它不起作用。序列化后,字典不包含任何值。

public class Datamap
{
    [JsonProperty("datamapItems")]
    public List<DatamapItem> datamapItems { get; set; }
}

public class DatamapItem
{
    public Dictionary<object, object> datamapitems = new Dictionary<object, object>();
    public DatamapKey datamapKey { get; set; }
}
public class DatamapKey
{
    public Dictionary<object, object> datamapitems = new Dictionary<object, object>();
}

1 个答案:

答案 0 :(得分:0)

如果对象不是固定的并且数据必须是可配置的,那么Newtonsoft.json具有一个要在此处使用的功能,即[JsonExtensionData]Read more

  

现在,序列化对象时将写入扩展数据。读取和写入扩展数据可以自动往返所有JSON,而无需将所有属性添加到要反序列化的.NET类型。仅声明您感兴趣的属性,然后让扩展数据完成其余工作。

在这里,我创建了一个控制台应用程序用于演示。

class Program
{
    static void Main(string[] args)
    {
        //This is your input json string
        var inputJson = @"{
                      'datamapItems': [
                                   {
                                      'paramName': 'VE8321C',
                                      'datamapKey': {
                                                   'module': 1,
                                                   'id': 1391
                                      },
                                      'min': '0',
                                      'max': '40',
                                      'default': 222,
                                      'rateHz': 0,
                                      'timeoutMs': 0,
                                      'dataType': 'uint16'
                                    }
                                 ]
                           }";


        var result = JsonConvert.DeserializeObject<Datamap>(inputJson);  //Here you can deserialize your json


        DatamapKey datamapKey = new DatamapKey();
        datamapKey._DatamapKeys = new Dictionary<string, JToken>();
        datamapKey._DatamapKeys.Add("module", 1);
        datamapKey._DatamapKeys.Add("id", 1391);
        datamapKey._DatamapKeys.Add("ABC", 123);   //Here I added extra key/value pair to your inner object

        DatamapItem datamapItem = new DatamapItem();
        datamapItem._DatamapItems = new Dictionary<string, JToken>();
        datamapItem._DatamapItems.Add("paramName", "VE8321C");
        datamapItem._DatamapItems.Add("datamapKey", JToken.FromObject(datamapKey));
        datamapItem._DatamapItems.Add("min", "0");
        datamapItem._DatamapItems.Add("max", "40");
        datamapItem._DatamapItems.Add("default", 222);
        datamapItem._DatamapItems.Add("rateHz", 0);
        datamapItem._DatamapItems.Add("timeoutMs", 0);
        datamapItem._DatamapItems.Add("dataType", "uint16");

        datamapItem._DatamapItems.Add("PQR", "123");   //Here I added extra key/value pair to your outer object
        datamapItem._DatamapItems.Add("XYZ", "123");    //Here I added extra key/value pair to your outer object

        Datamap datamap = new Datamap();
        datamap.datamapItems = new List<DatamapItem>();
        datamap.datamapItems.Add(datamapItem);

        string json = JsonConvert.SerializeObject(datamap);   //Here you can serialize your custom key/value pair 

        JObject parsed = JObject.Parse(json);
        Console.WriteLine(parsed);

        Console.ReadLine();
    }
}

public class DatamapKey
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _DatamapKeys;
}

public class DatamapItem
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _DatamapItems;
}

public class Datamap
{
    public List<DatamapItem> datamapItems { get; set; }
}

输出:

enter image description here

编辑:

1)对于json以下

{ "agentRegistry": { "agents": [ { "type": "drv", "id": "drv3", "port": 3, "config": { "mode": "currentSetPoint", "config": { } } }, { "type": "mmc", "id": "mmc2", "port": 2, "config": { "mode": "analogIn", "config": { "max": 21000, "min": 300, "conversion": [ ] } }}]}}

课程:

public class Config2
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _config2;
}

public class Config
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _config;
}

public class Agent
{
    [JsonExtensionData]
    public IDictionary<string, JToken> _agents;
}

public class AgentRegistry
{
    public List<Agent> agents { get; set; }
}

public class RootObj
{
    public AgentRegistry agentRegistry { get; set; }
}