数组到JSON(键/值)



我想在c#代码中实现数组到JSON对象的转换。

Array: [a,b,c,d,e,f]

Json:{"a":"b","c":"d","e":"f"}

我尝试使用newtonsoft序列化数组,输出不是键值格式。输入是一个字符串数组,输出需要JSON格式的键/值格式。

给定一个string []数组,您可以使用LINQ将其转换为字典,然后对字典进行序列化。

。使用json.net:

var dictionary = array.AsPairs().ToDictionary(t => t.Key, t => t.Value);
var newJson = JsonConvert.SerializeObject(dictionary, Formatting.Indented);

在这里演示小提琴#1。

或者,使用system.text.json序列化:

var newJson = JsonSerializer.Serialize(dictionary, new JsonSerializerOptions { WriteIndented = true });

在这里演示小提琴#2。

两个选项都使用扩展方法:

public static class EnumerableExtensions
{
public static IEnumerable<(T Key, T Value)> AsPairs<T>(this IEnumerable<T> enumerable)
{
return AsPairsEnumerator(enumerable ?? throw new ArgumentNullException());
static IEnumerable<(T key, T value)> AsPairsEnumerator(IEnumerable<T> enumerable)
{
bool saved = false;
T key = default;
foreach (var item in enumerable)
{
if (saved)
yield return (key, item);
else
key = item;
saved = !saved;
}
}
}
}

并生成结果

{
"a": "b",
"c": "d",
"e": "f"
}

最新更新