• 键值对解析


    /// <summary>
    /// 键值对解析Helper,修改matchKey作为键值之间的符号,matchValue为键值对之间的符号
    /// </summary>
    public static class KeyValueHelper
    {
    static Dictionary<object, object> conents = new Dictionary<object, object>();
    public static string matchKey { get; set; }
    public static string matchValue { get; set; }

    /// <summary>
    /// 解析输入Bytes中的键值对
    /// </summary>
    /// <param name="data">输入字节数组</param>
    /// <returns>解析后的键值对字典</returns>
    public static Dictionary<object, object> GetConentByBytes(byte[] data)
    {
    conents.Clear();
    conents = GetConentByString(Encoding.Default.GetString(data));
    return conents;
    }

    /// <summary>
    /// 解析输入字符串中的键值对
    /// </summary>
    /// <param name="data">输入字符串</param>
    /// <returns>解析后的键值对字典</returns>
    public static Dictionary<object, object> GetConentByString(string data)
    {
    conents.Clear();

    if (data.Substring(data.Length - 1) != matchValue)
    {
    data = data + matchValue;
    }

    try
    {
    int pos = 0;
    int startIndex = 0;
    while (true)
    {
    //Get Key
    pos = data.IndexOf(matchKey, startIndex);
    string key = data.Substring(startIndex, pos - startIndex);
    startIndex = pos + 1;
    //Get Value
    pos = data.IndexOf(matchValue, startIndex);
    string value = data.Substring(startIndex, pos - startIndex);
    startIndex = pos + 1;
    conents.Add(key, value);

    if (startIndex >= data.Length)
    {
    break;
    }
    }
    }
    catch (Exception ex)
    {
    throw new Exception("Error Info: " + ex.ToString());
    }

    return conents;
    }
    }

    //uesrId=1&datetime=2019-10-14 11:43:56&sign=123456sdfsdgdsgsdgfsd

    Request.Content.ReadAsStreamAsync().Result.Seek(0, System.IO.SeekOrigin.Begin);
    string content = Request.Content.ReadAsStringAsync().Result;

    KeyValueHelper.matchKey = "=";
    KeyValueHelper.matchValue = "&";
    Dictionary<object, object> conents = KeyValueHelper.GetConentByString(content);
    string str = Newtonsoft.Json.JsonConvert.SerializeObject(conents);
    JObject obj = JObject.Parse(str);

    太麻烦了,来回转好几次,如果没有必要就不要用这种了,我只是想研究一下API POST接收键值对参数,不用定义类的的一种方式,欢迎来喷!!

  • 相关阅读:
    你真的会写二分查找吗
    深入理解C++对象模型
    python监控ip攻击,服务器防火墙
    python操作redis
    python操作mysql
    jmeter_linux下运行
    chales抓包,模拟异常情况
    python正则表达式
    python-笔记(六)模块操作以及常用模块简介
    fpython-笔记(五)装饰器、匿名函数
  • 原文地址:https://www.cnblogs.com/ztf20/p/11926815.html
Copyright © 2020-2023  润新知