你好,我有一本正在使用的字典。
Dictionary<string, string> myProperties
我正在尝试将其格式化为 JSON,但遇到了困难。我需要它是这样的:
{
"properties": [
{
"property": "firstname",
"value": "John"
},
{
"property": "lastname",
"value": "Doe"
},
{
"property": "country",
"value": "united states"
}
]
}
目前我正在使用 Json.NET 来序列化字典,但这给了我这个:
{
"country": "united states",
"firstname": "John",
"lastname": "Doe"
}
谁能帮我把它格式化成我需要的格式。任何帮助将不胜感激。
最佳答案
您可以通过将 .Select()
的结果发送到包装在匿名类中的 json 序列化程序来实现这一目标,但如果您打算构建更大的东西,我建议您使用真实的类。
JsonConvert.SerializeObject(
new {properties = myProperties.Select(kv => new { property = kv.Key, value = kv.Value})}
,Formatting.Indented);
这会给你
{
"properties": [
{
"property": "firstname",
"value": "John"
},
{
"property": "lastname",
"value": "Doe"
},
{
"property": "country",
"value": "united states"
}
]
}
关于c# - 来自字典 C# 的 Json 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48652202/