当前位置:首页 > 技能相关 > C#与C++ > 正文内容

C# 实现JSON转换特定字符串并Ascii排序

admin1年前 (2024-01-05)C#与C++3470 修订时间:2024-01-05 13:46:31

规则

1.参数名ASCII码从小到大排序

2.参数名区分大小写

3.转换格式:属性=值&属性=值&属性=值

实现

1、参数名ASCII码从小到大排序

使用Newtonsoft.Json序列化的JSON,除非人为指定排序规则,则默认为AsciiAsc排序方式。C# 使用Newtonsoft.Json进行对象序列化、JSON反序列化的方法

我们可以这么实现,示例代码:

1.1 json代码(也可使用Newtonsoft.Json序列化类对象):

{
  "nonceStr": "z0o66TGb08u10i8pwk5Rr",
  "authAppKey": "Pny5BAdcrZH1KDSU2VbhAF",
  "timestamp": "1668783983693"
}

2、json转Dictionary<string, string>

string json = JSON串
var Attributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

使用Newtonsoft.Json的反序列化JsonConvert.DeserializeObject<Dictionary<string, string>>(json)转换为Dictionary<string, string>格式;

3、转换Dictionary<string, string>为特定格式

示例格式(AsciiAsc):

authAppKey=Pny5BAdcrZH1KDSU2VbhAF&nonceStr=z0o66TGb08u10i8pwk5Rr&timestamp=1668783983693

Ascii排序从小到大

private static String AsciiAsc(Dictionary<String, String> dic)
{
    //Ascii升序排序
    var sortResult3 = from pair in dic orderby pair.Key ascending select pair;
    StringBuilder sb = new StringBuilder();
    foreach (KeyValuePair<String, String> p in sortResult3)
    {
      //格式化输出生成串
      sb.Append(p.Key).Append("=").Append(p.Value).Append('&');
    }
    //去除末尾多余字符
    string ls_str = sb.ToString();
    ls_str = ls_str.Substring(0, ls_str.Length - 1);
    return ls_str;
}

Ascii排序从大到小

private static String AsciiAsc(Dictionary<String, String> dic)
{
    //Ascii降序排序
    var sortResult3 = from pair in dic orderby pair.Key descending select pair;
    StringBuilder sb = new StringBuilder();
    foreach (KeyValuePair<String, String> p in sortResult3)
    {
      //格式化输出生成串
      sb.Append(p.Key).Append("=").Append(p.Value).Append('&');
    }
    //去除末尾多余字符
    string ls_str = sb.ToString();
    ls_str = ls_str.Substring(0, ls_str.Length - 1);
    return ls_str;
}
 您阅读本篇文章共花了: 

免责声明
本站内容均为博客主本人日常使用记录的存档,如侵犯你的权益请联系:lifei@zaiheze.com 546262132@qq.com 沟通删除事宜。本站仅带访问端口形式使用,已杜绝搜索引擎爬取。

扫描二维码推送至手机访问。

版权声明:本文由LIFEI - blog发布,如需转载请注明出处。

本文链接:http://www.lifeiai.com/?id=382

分享给朋友:

相关文章

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。