C#排序JSON字符串键

Edu*_*lho 8 .net c# sorting string json

我想转换JSON字符串

"{ \"birthday\": \"1988-03-18\", \"address\": { \"state\": 24, \"city\": 8341, \"country\": 1 } }"
Run Code Online (Sandbox Code Playgroud)

"{ \"address\": { \"city\": 8341, \"country\": 1, \"state\": 24 }, \"birthday\": \"1988-03-18\" }"
Run Code Online (Sandbox Code Playgroud)

注意:我没有使用排序版本进行通信(因为密钥顺序并不重要),我需要一个排序版本来执行本地测试(通过比较JSON字符串).


编辑: I4V指出一个使用Json.Net的解决方案,我宁愿使用一个不需要包含任何第三方库的解决方案(实际上我在我的应用程序中使用内置的System.Json)


我张贴由I4V +一些测试提供的解决方案要点这里.谢谢你们.

I4V*_*I4V 14

我会用Json.Net

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();
Run Code Online (Sandbox Code Playgroud)
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);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

尝试System.Json但我不确定OrderByDescending(或OrderBy).

var jObj = (System.Json.JsonObject)System.Json.JsonObject.Parse(json);
Sort2(jObj);
var newJson = jObj.ToString();
Run Code Online (Sandbox Code Playgroud)
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);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我知道这可能有点晚了,但是,如果您也需要对内部数据数组进行排序(我只是需要它):

static 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);
        if (prop.Value is JArray)
        {
            Int32 iCount = prop.Value.Count();
            for (Int32 iIterator = 0; iIterator < iCount; iIterator++)
                if (prop.Value[iIterator] is JObject)
                    Sort((JObject)prop.Value[iIterator]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

干杯!