gpt4 book ai didi

json.net - 将 Dictionary<,> 序列化为 Json.NET 中的数组

转载 作者:行者123 更新时间:2023-12-04 11:54:00 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Serialize dictionary as array (of key value pairs)

(6 个回答)


5年前关闭。




如何让 Json.NET 序列化程序进行序列化 IDictionary<,>实例化为具有键/值属性的对象数组?
默认情况下,它将 Key 的值序列化为 JSON 对象的属性名称。

基本上我需要这样的东西:

[{"key":"some key","value":1},{"key":"another key","value":5}]

代替:
{{"some key":1},{"another key":5}}

我尝试添加 KeyValuePairConverter到序列化程序设置,但没有效果。 (我发现这个转换器对于 IDictionary<> 的类型被忽略了,但我无法轻易更改我的对象的类型,因为它们是从其他库接收的,因此从 IDictionary<> 更改为 ICollection<KeyValuePair<>> 不是我的选择。)

最佳答案

我能够让这个转换器工作。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class CustomDictionaryConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (typeof(IDictionary).IsAssignableFrom(objectType) ||
TypeImplementsGenericInterface(objectType, typeof(IDictionary<,>)));
}

private static bool TypeImplementsGenericInterface(Type concreteType, Type interfaceType)
{
return concreteType.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Type type = value.GetType();
IEnumerable keys = (IEnumerable)type.GetProperty("Keys").GetValue(value, null);
IEnumerable values = (IEnumerable)type.GetProperty("Values").GetValue(value, null);
IEnumerator valueEnumerator = values.GetEnumerator();

writer.WriteStartArray();
foreach (object key in keys)
{
valueEnumerator.MoveNext();

writer.WriteStartObject();
writer.WritePropertyName("key");
writer.WriteValue(key);
writer.WritePropertyName("value");
serializer.Serialize(writer, valueEnumerator.Current);
writer.WriteEndObject();
}
writer.WriteEndArray();
}

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

以下是使用转换器的示例:
IDictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("some key", 1);
dict.Add("another key", 5);

string json = JsonConvert.SerializeObject(dict, new CustomDictionaryConverter());
Console.WriteLine(json);

这是上面的输出:
[{"key":"some key","value":1},{"key":"another key","value":5}]

关于json.net - 将 Dictionary<,> 序列化为 Json.NET 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18385325/

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