【问题标题】:Convert Key-Value Pair String to .NET Object将键值对字符串转换为 .NET 对象
【发布时间】:2020-09-27 17:08:15
【问题描述】:

我有一个这样的 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 类型?

【问题讨论】:

  • 第二个对象中似乎没有使用“Status”道具,我看到“Key”设置为“Status”,您确定正在使用“Status”吗?
  • @OttoCheley 每个属性都在使用中。对不起,我不明白这是否重要?无论如何,我仍然需要访问该值。

标签: c# .net json serialization deserialization


【解决方案1】:

你可以做这样的事情。创建一个新类,将获得的 JSON 反序列化为一类 KeyValue 对。然后根据您感兴趣的键从此类中获取值。


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.

注意:根据惯例,类中的变量名应使用大写首字母。使用 JsonProperty 有助于符合该标准。

【讨论】:

  • 这个答案很好,因为对于 CustomObject,您可以从 json 中选择您想要的值。如果CustomObject 中有很多属性,我希望你能看到这可能有点乏味。有没有更精简的方式?
  • @Bmoe 在 CustomObject 类中添加了一个构造函数,该构造函数使用反射来更新 json 中可能存在或不存在的所有属性.. 请参阅上面的更新回复
猜你喜欢
  • 1970-01-01
  • 2023-01-12
  • 2017-03-26
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
相关资源
最近更新 更多