C# JSON根据键的ASCII码进行排序
要求:
1、按照第一个字符的键值 ASCII 码递增排序(字母升序排序),如果遇到相同字符则按照第二个字符的键值 ASCII 码递增排序,以此类推。
2、所有节点数据字段均需要排序,即所有子节点和深度底层节点的数据字段。
方法一
static void Main(string[] args)
{
JObject jObject = new JObject()
{
{ "ptId", "12345678" },
{ "ptName", "Test" },
{ "pta", "0000" },
};
SortedDictionary<string, object> target = KeySort(jObject);
string strPostData = JsonConvert.SerializeObject(target);
JObject newJ = JObject.Parse(strPostData);
Console.WriteLine(newJ);
}
private static SortedDictionary<string, object> KeySort(JObject obj)
{
// 重点在于增加了一个 StringComparer.Ordinal 属性
var res = new SortedDictionary<string, object>(StringComparer.Ordinal);
foreach (var x in obj)
{
if (x.Value is JValue) res.Add(x.Key, x.Value);
else if (x.Value is JObject @object) res.Add(x.Key, KeySort(@object));
else if (x.Value is JArray)
{
JArray jArray = (JArray)x.Value;
var tmp = new SortedDictionary<string, object>[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
tmp[i] = KeySort((JObject)x.Value[i]);
}
res.Add(x.Key, tmp);
}
}
return res;
}
方法二:
static void Main(string[] args)
{
JObject jObject = new JObject()
{
{ "ptId", "12345678" },
{ "ptName", "Test" },
{ "pta", "0000" },
};
// 同样的使用了 StringComparer.Ordinal 属性
var sk = obj.Properties().OrderBy(p => p.Name, StringComparer.Ordinal);
JObject newJ = new JObject();
foreach (var item in sk)
{
newJ.Add(item);
}
Console.WriteLine(newJ);
}
方法三:
namespace MyNameSpace
{
public class Program()
{
static void Main(string[] args)
{
JObject jObject = new JObject()
{
{ "ptId", "12345678" },
{ "ptName", "Test" },
{ "pta", "0000" },
};
}
private static SortedDictionary<string, object> KeySort(JObject obj)
{
// 使用比较器
// 这种方法可以用来实现更复杂的排序,在这里只是提供一种思路
var res = new SortedDictionary<string, object>(new AsciiCompare());
foreach (var x in obj)
{
if (x.Value is JValue) res.Add(x.Key, x.Value);
else if (x.Value is JObject @object) res.Add(x.Key, KeySort(@object));
else if (x.Value is JArray)
{
JArray jArray = (JArray)x.Value;
var tmp = new SortedDictionary<string, object>[jArray.Count];
for (var i = 0; i < jArray.Count; i++)
{
tmp[i] = KeySort((JObject)x.Value[i]);
}
res.Add(x.Key, tmp);
}
}
return res;
}
}
// 增加一个比较器
public class AsciiCompare : IComparer<string>
{
public int Compare(string x, string y)
{
return string.CompareOrdinal(x, y);
}
}
}