简体   繁体   English

JSON序列化属性对象放入键和值列表

[英]JSON Serialization Proprty object into Key and Value list

I am struggling to change one list in to the form of Key and Value. 我正在努力将一个列表更改为“键和值”形式。

As an example: I have a List Property object 例如:我有一个列表属性对象

public List<Details> Details{get;set;}
public class Details
{
 public string FirstName{get;set;}
 public string LastName{get;set;}
}

I am looking for a JSON string using this object in the below Format: 我正在使用以下格式的此对象寻找JSON字符串:

{"Details":[
{"Key":"FirstName" ,"Value":"value in list object"},
{"Key":"LastName" ,"Value":"value in list object"}
]}

I am unable to achieve it using JSON serialization. 我无法使用JSON序列化来实现。 Is there any way to achieve it using any type of available serialization ? 有什么方法可以使用任何类型的可用序列化来实现它吗?

Thanks guys in advance. 预先谢谢你们。

To be begin with, the output sample given isn't quite a valid Json as its missing "{" and "}" at either end. 首先,给定的输出样本并不是有效的Json,因为其两端都缺少“ {”和“}”。

You could achieve the above format using Custom Json Converter and a wrapping Anonymous type before serializing. 您可以在序列化之前使用Custom Json Converter和包装的Anonymous类型实现上述格式。 For example, 例如,

Consider the following JsonConverter. 考虑以下JsonConverter。

public class KeysJsonConverter : JsonConverter
{
    private readonly Type[] _types;

    public KeysJsonConverter(params Type[] types)
    {
        _types = types;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken token = JToken.FromObject(value);

        if(token.Type == JTokenType.Object)
        {
            JObject oldValue = (JObject)token;
            JObject newValue = new JObject();
            var jkey = oldValue.Properties().Select(x=>x.Name).First();
            var jvalue = oldValue.Properties().Select(x=>x.Value).First();

            newValue.AddFirst(new JProperty("Key",jkey));
            newValue.Add(new JProperty("Value",jvalue));
            newValue.WriteTo(writer);

        }
        return;

    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return _types.Any(t => t == objectType);
    }
}

You can now serialize the collection using following. 您现在可以使用以下方法序列化集合。

var result = JsonConvert.SerializeObject(details, 
                   Newtonsoft.Json.Formatting.Indented, 
                   new KeysJsonConverter(typeof(Details)));

This would produce an output as following. 这将产生如下输出。

[
  {
    "Key": "FirstName",
    "Value": "Anu"
  },
  {
    "Key": "FirstName",
    "Value": "Jia"
  }
]

In order to wrap the Json with "Details" key as in OP, you could wrap your collection within an anonymous type. 为了像在OP中那样用“ Details”键包装Json,可以将集合包装在匿名类型中。 For example, 例如,

var result = JsonConvert.SerializeObject(new {Details=details}, 
                             Newtonsoft.Json.Formatting.Indented, 
                             new KeysJsonConverter(typeof(Details)));

Output Sample, 输出样本

{
  "Details": [
    {
      "Key": "FirstName",
      "Value": "Anu"
    },
    {
      "Key": "FirstName",
      "Value": "Jia"
    }
  ]
}

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

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