C#排序JSON字符串键 [英] C# Sort JSON string keys
问题描述
我想JSON字符串转换
I'd like to convert the JSON string
"{ \"birthday\": \"1988-03-18\", \"address\": { \"state\": 24, \"city\": 8341, \"country\": 1 } }"
到
"{ \"address\": { \"city\": 8341, \"country\": 1, \"state\": 24 }, \"birthday\": \"1988-03-18\" }"
请注意:我不使用通讯排序的版本(因为键顺序并不重要),我需要一个有序的版本进行本地测试(通过比较JSON字符串)。
NOTE: I'm not using the sorted version for communication (because the key order doesn't really matter), I need a sorted version to perform local tests (by comparing JSON strings).
编辑: I4V指出使用的Json的解决方案。净,我宁可使用不必包含任何第三方库(其实我使用的是内置的System.Json在我的应用程序)
I4V pointed a solution that uses Json.Net, I would rather use a solution that doesn't need to include any 3rd party library (actually I'm using the built in System.Json in my application)
我张贴由I4V +一些测试的这里。谢谢大家。
I posted a gist with the solution provided by I4V + some testing here. Thank you all.
推荐答案
我将使用的Json此
I will use Json.Net for this
string json = @"{ ""birthday"": ""1988-03-18"", ""address"": { ""state"": 24, ""city"": 8341, ""country"": 1 } }";
var jObj = (JObject)JsonConvert.DeserializeObject(json);
Sort(jObj);
string newJson = jObj.ToString();
void Sort(JObject jObj)
{
var props = jObj.Properties().ToList();
foreach (var prop in props)
{
prop.Remove();
}
foreach (var prop in props.OrderBy(p=>p.Name))
{
jObj.Add(prop);
if(prop.Value is JObject)
Sort((JObject)prop.Value);
}
}
修改
一个尝试与 System.Json
,但我不知道关于 OrderByDescending
(或排序依据
)。
A try with System.Json
but I am not sure about OrderByDescending
( or OrderBy
).
var jObj = (System.Json.JsonObject)System.Json.JsonObject.Parse(json);
Sort2(jObj);
var newJson = jObj.ToString();
void Sort2(System.Json.JsonObject jObj)
{
var props = jObj.ToList();
foreach (var prop in props)
{
jObj.Remove(prop.Key);
}
foreach (var prop in props.OrderByDescending(p => p.Key))
{
jObj.Add(prop);
if (prop.Value is System.Json.JsonObject)
Sort2((System.Json.JsonObject)prop.Value);
}
}
这篇关于C#排序JSON字符串键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!