gpt4 book ai didi

c# - 如何将自定义列表类转换为 json?

转载 作者:行者123 更新时间:2023-11-30 20:51:31 25 4
gpt4 key购买 nike

我有以下类(class)(有点简化的版本):

public class DemoList<K, V>
{
private List<SomeItem<K, V>> _listItems;

public DemoList()
{
_listItems = new List<SomeItem<K, V>>();
}
public Int32 Count
{
get { return _listItems.Count; }
}
public void Add(SomeItem<K, V> item)
{
_listItems.Add(item);
}
public SomeItem<K, V> this[int index]
{
get { return _listItems[index]; }
}
}

SomeItem 代码:​​

public class SomeItem<K, V>
{
private K _key;
private V _value;
public SomeItem(K key, V value)
{
_key = key;
_value = value;
}
public K Key
{
get { return _key; }
set { _key = value; }
}
public V Value
{
get { return _value; }
set { _value = value; }
}
}

当我向演示列表添加一些值时:

DemoList<String, String> dl = new DemoList<string, string>();
dl.Add(new SomeItem<string, string>("bla1", "diebla1"));
dl.Add(new SomeItem<string, string>("bla2", "diebla2"));
dl.Add(new SomeItem<string, string>("bla3", "diebla3"));
dl.Add(new SomeItem<string, string>("bla4", "diebla4"));

现在我想使用 NewtonSoft.Json 将其转换为 json ... 如下所示:

JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var jsonContent = JsonConvert.SerializeObject(dl, serializerSettings);

这会产生以下 JSON:

{"Count":4}

我希望得到的 json 是这样的:

{
"items": [
{ "bla1": "diabla1"},
{"bla2": "diabla2"},
{"bla3": "diabla3"},
{"bla4": "diabla4"}
]
}

有什么想法吗?

最佳答案

要让 Json.Net 序列化项目列表,您可以将项目公开为公共(public)属性(正如其他人所建议的那样),或者使用 [JsonProperty] 属性标记列表,例如所以:

    [JsonProperty("items")]
private List<SomeItem<K, V>> _listItems;

如果您想从输出中抑制 Count,请使用 [JsonIgnore] 标记该属性:

    [JsonIgnore]
public Int32 Count
{
get { return _listItems.Count; }
}

通过上述更改,我们得到以下 JSON,它更接近,但仍然不是您想要的:

{
"items": [
{ "key": "bla1", "value": "diebla1" },
{ "key": "bla2", "value": "diebla2" },
{ "key": "bla3", "value": "diebla3" },
{ "key": "bla4", "value": "diebla4" }
]
}

要将项目转换为您想要的格式,您需要一个自定义 JsonConverter 类,如下所示:

class SomeItemConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType &&
objectType.GetGenericTypeDefinition() == typeof(SomeItem<,>);
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken token = JToken.FromObject(value);
JObject obj = new JObject();
obj.Add(token["Key"].ToString(), token["Value"]);
obj.WriteTo(writer);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
JProperty prop = token.Children<JProperty>().First();
JObject obj = new JObject();
obj.Add("Key", prop.Name);
obj.Add("Value", prop.Value);
return obj.ToObject(objectType);
}
}

将转换器添加到您的 JsonSerializerSettings 并像以前一样序列化您的列表:

JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
serializerSettings.Converters.Add(new SomeItemConverter());
var jsonContent = JsonConvert.SerializeObject(dl, serializerSettings);
Console.WriteLine(jsonContent);

现在我们有了这个 JSON:

{
"items": [
{ "bla1":"diebla1" },
{ "bla2":"diebla2" },
{ "bla3":"diebla3" },
{ "bla4":"diebla4" }
]
}

关于c# - 如何将自定义列表类转换为 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21628669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com