将JSON文件反序列化为包含具有动态键的字典的类

时间:2019-06-28 16:49:22

标签: c# json dictionary serialization json.net

我正在尝试使用Newtonsoft将JSON文件反序列化为c#中的对象,该对象的结构与文件本身略有不同。

文件的结构如下:

PointProperty:
{
    "DataPointType": Foo
    "PointTypeProperties: [
          {
               "PropertyName":
               "PropertyValue":
               "Requirement":
          },
          etc.
     ]
}

我正在尝试将JSON文件序列化为PointProperty和PointTypeProperty类:

    public class PointProperty
    {
        public string DataPointType { get; set; }

        public Dictionary<String,PointTypeProperty> PointTypeProperties { get; set; }
    }

    public class PointTypeProperty
    {
        public string PropertyValue { get; set; }
        public string Requirement { get; set; }

    }

在某种程度上,指向PointTypeProperties字典的键将是JSON文件中的PropertyName。我可以使用自定义解串器来实现此目的吗?

例如:

PointProperty:
{
    "DataPointType": Alarm
    "PointTypeProperties: [
          {
               "PropertyName": AlarmCheck
               "PropertyValue": False
               "Requirement": Mandatory
          },
          etc.
     ]
}

将反序列化为类似的类:

``

public class PointTypeProperty
{
    public string PropertyValue = False
    public string Requirement = Mandatory

}

public class PointProperty
{
    public string DataPointType = Alarm

    public Dictionary<String,PointTypeProperty> PointTypeProperties = {"AlarmCheck": PointTypeProperty}
}

1 个答案:

答案 0 :(得分:0)

您不需要自定义序列化程序。您可以使用DTO,可以轻松地将其转换为您的班级。

PointTypeProperties从逻辑上讲是JSON中的一个数组,因此请创建一个对该数组进行建模的DTO:

public class PointPropertyDto
{
    public string DataPointType { get; set; }
    public PointTypePropertyDto[] PointTypeProperties { get; set; }
}

public class PointTypePropertyDto
{
    public string PropertyName { get; set; }
    public string PropertyValue { get; set; }
    public string Requirement { get; set; }
}

将JSON反序列化为DTO图:

string json = @"
{
    ""DataPointType"": ""Foo"",
    ""PointTypeProperties"": [
          {
               ""PropertyName"": ""Some name"",
               ""PropertyValue"": ""Some value"",
               ""Requirement"": ""Some requirement""
          }
     ]
}";

var deserializedDto = JsonConvert.DeserializeObject<PointPropertyDto>(json);

然后,从DTO转换为原始类:

var deserialized = new PointProperty
{
    DataPointType = deserializedDto.DataPointType,
    PointTypeProperties = deserializedDto.PointTypeProperties.ToDictionary(p => p.PropertyName, p =>
        new PointTypeProperty
        {
            PropertyValue = p.PropertyValue,
            Requirement = p.Requirement
        })
};