序列化名称-值对的列表,不包括键和值部分



我有低于的类

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace mynamespace
{
public class Incident
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("components")]
public List<KeyValuePair<string, string>> Components { get; set; }
public Incident()
{
Components = new List<KeyValuePair<string, string>>();
}
}
}

如果我有一个对象,其中我添加了一个键为ddd、值为dssds的NameValuePair。。。

将其转换为Json 时

我目前有

{
"name": "test",
"components": [{ "Key": "ddd", "Value": "dssds" }]
}

我需要

{
"name": "test",
"components": {
"ddd": "dssds"
}
}

我用序列化

var json = JsonConvert.SerializeObject(incident);

我该怎么做?我想我需要某种转换器?

一个建议是

var test = new { name = incident.Name, components = incident.Components.Select(i => i.Value) };
var json = JsonConvert.SerializeObject(test);

这会生成

{
"name":"test",
"components":["dssds"]
}

这与上我需要的json不匹配

Paul

要获得所需的输出,Components需要是Dictionary<string, string>而不是List<KeyValuePair<string, string>>。因此,最简单的解决方案是将类更改为这种效果:

public class Incident
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("components")]
public Dictionary<string, string> Components { get; set; }
public Incident()
{
Components = new Dictionary<string, string>();
}
}

Fiddle:https://dotnetfiddle.net/Mx4Z8U

当然,这个解决方案的缺点是,您现在必须更新所有使用Incident的代码,以便使用Dictionary而不是List。根据依赖项的数量,您可能想这样做,也可能不想这样做。

因此,第二个最简单的解决方案是在使用List<KeyValuePair<string, string>>作为数据源的类中创建代理Dictionary<string, string>属性。如果你愿意,它可以是私人的。将[JsonProperty("components")]属性移动到新的Dictionary,并用[JsonIgnore]标记List<KeyValuePair<string, string>>。所以你会有这个:

public class Incident
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonIgnore]
public List<KeyValuePair<string, string>> Components { get; set; }
[JsonProperty("components")]
private Dictionary<string, string> ComponentDictionary
{
get { return Components != null ? new Dictionary<string, string>(Components) : null; }
}
public Incident()
{
Components = new List<KeyValuePair<string, string>>();
}
}

Fiddle:https://dotnetfiddle.net/Po22Yt

最新更新