C#排序JSON字符串键
我想转换JSON字符串
"{ \"birthday\": \"1988-03-18\", \"address\": { \"state\": 24, \"city\": 8341, \"country\": 1 } }"
至
"{ \"address\": { \"city\": 8341, \"country\": 1, \"state\": 24 }, \"birthday\": \"1988-03-18\" }"
注意:我没有使用排序版本进行通信(因为密钥顺序并不重要),我需要一个排序版本来执行本地测试(通过比较JSON字符串)。
编辑: I4V指出一个使用Json.Net的解决方案,我宁愿使用一个不需要包含任何第三方库的解决方案(实际上我在我的应用程序中使用内置的System.Json)
我发布了一个关于I4V提供的解决方案的要点+一些测试。 谢谢你们。
我将使用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();
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
(或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); } }
通过使用此方法,您可以使用json数据检索动态对象
在DynamicJsonConverter
创建一个SortedDictionary
var d = new SortedDictionary(dictionary); // TODO: code to sort inner objects return new DynamicJsonObject(d);
然后你可以使用
string jsonStr = "{\"B\":\"2\",\"A\":\"1\"}"; JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); dynamic json = jss.Deserialize(jsonStr, typeof(object)) as dynamic; string result = new JavaScriptSerializer().Serialize((json as DynamicJsonObject).Dictionary);
result
将具有预期的输出。
我知道这可能有点晚了,但是如果你需要对内部数据数组进行排序(我只需要它):
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]); } } }
干杯!