将键值对字符串转换为.NET对象

时间:2020-06-08 16:44:26

标签: c# .net json serialization deserialization

我有一个像这样的json字符串(有很多属性,但只包含几个值):[{"Key":"ID","Value":"123"},{"Key":"Status","Value":"New"},{"Key":"Team","Value":"South"}]

我有一个表示值的类

    public class CustomObject
        {
            public string ID { get; set; }
            public string Status { get; set; }
            public string Team { get; set; }
//Other props

        }

因此,即使JSON是包含Key:x, Value:y的这些对象的数组,整个结构实际上只是我的CustomObject类的实例。这就是json给我的方式。如何将其转换为CustomObject类型?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作。创建一个新的类,该类将反序列化获得的KeyValue对类的JSON。然后根据您感兴趣的键从此类中获取值。


public class CustomObject
{
    public CustomObject() { }

    public CustomObject(List<KeyValueClass> jsonObject) // Use of Reflection here
    {
        foreach (var prop in typeof(CustomObject).GetProperties())
        {
            prop.SetValue(this, jsonObject.FirstOrDefault(x => x.Key.Equals(prop.Name))?.Value, null);
        }
    }

    public string ID { get; set; }
    public string Status { get; set; }
    public string Team { get; set; }

}

public class KeyValueClass
{
    [JsonProperty("Key")]
    public string Key { get; set; }

    [JsonProperty("value")]
    public string Value { get; set; }
}

以及以下是您将其反序列化的方式。


var obj = JsonConvert.DeserializeObject<List<KeyValueClass>>(json);
var customObj = new CustomObject()
{
    ID = obj.FirstOrDefault(x => x.Key.Equals("ID"))?.Value,
    Status = obj.FirstOrDefault(x => x.Key.Equals("Status"))?.Value,
    Team = obj.FirstOrDefault(x => x.Key.Equals("Team"))?.Value
};

var customObj2 = new CustomObject(obj); // Using constructor to build your object.

注意:根据约定,您应该在类中的变量名称中使用UpperCase首字母。使用JsonProperty有助于符合该标准。