请教c#,本人该怎么样把在dictionary里排好序的值进行首位拼接

.Net技术 码拜 7年前 (2017-04-28) 1253次浏览
例如:这串json{
“b2”: “b222”,
“a1”: “a111”,
“d4”: “d444”,
“e5”: [
{
“bb2”: “b2222”,
“aa1”: “a1111”,
“cc3”: “c3333”
},
{
“bb2”: “b2222”,
“aa1”: “a1111”,
“cc3”: “c3333”
}
]
}
本人需要把他按照键名顺序从a-z排序,然后把他们的键值根据排好后的顺序进行拼接。
排序:{
“a1”: “a111”,
“b2”: “b222”,
“d4”: “d444”,
“e5”: [
{
“aa1”: “a1111”,
“bb2”: “b2222”,
“cc3”: “c3333”
},
{
“aa1”: “a1111”,
“bb2”: “b2222”,
“cc3”: “c3333″
}
]
}
最终获取键值并拼接得到结果:”a111b222d444a1111b2222c3333a1111b2222c3333”
本人现在的问题就是已经把json排好序了,现在不知道该怎么拼接,求高手指点请教c#,本人该怎么样把在dictionary里排好序的值进行首位拼接
解决方案

5

StringBuilder ConcatJson( Dictionary<string,object> JsonObject)
{
StringBuilder  builder=new StringBuilder  ();
foreach(var obj in JsonObject)
{
if (obj .Value is string )
{
builder.Append(obj .Value.ToString());
}
if (obj .Value is Dictionary<string,object>[] )
{
foreach(var dic in obj .Value as Dictionary<string,object>[])
{
builder.Append(ConcatJson(dic) );
}
}
if (obj .Value is Dictionary<string,object> )
{
builder.Append(ConcatJson(obj .Value as Dictionary<string,object>));
}
}
}

95

        static List<string> GetValue(SortedDictionary<string, object> inp)
        {
            var res = new List<string>();
            foreach (var x in inp)
            {
                if (x.Value is JValue) res.Add(x.Value.ToString());
                else if (x.Value is SortedDictionary<string, object>) res.AddRange(GetValue((SortedDictionary<string, object>)x.Value));
                else if (x.Value is SortedDictionary<string, object>[])
                {
                    var t = x.Value as SortedDictionary<string, object>[];
                    for (var i = 0; i < t.Length; i++)
                    {
                        res.AddRange(GetValue((SortedDictionary<string, object>)t[i]));
                    }
                }
            }
            return res;
        }

调用

            var s = File.ReadAllText("json.txt");//, Encoding.Default);
            var a = JObject.Parse(s);
            var target = KeySort(a);
            Console.WriteLine(string.Join("", GetValue(target)));

123456CNYcc@cc.comIDCARD付款人姓名30000苹果6Iphone 65易汇金备注1475142274858


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明请教c#,本人该怎么样把在dictionary里排好序的值进行首位拼接
喜欢 (0)
[1034331897@qq.com]
分享 (0)