• 键值对解析


    /// <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接收键值对参数,不用定义类的的一种方式,欢迎来喷!!

  • 相关阅读:
    Docker 日志都在哪里?怎么收集?
    docker link 过时不再用了?那容器互联、服务发现怎么办?
    Centos7.0 配置docker 镜像加速
    使用docker搭建公司redmine服务器
    Jenkins pipeline:pipeline 使用之语法详解
    Xcode脚本自动化打包问题:xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH
    java基础(7)---IO流
    java基础(6)---面向对象,类,包
    java基础(5)---内存分配
    java基础(4)---引用数据类型(数组、字符串、集合)
  • 原文地址:https://www.cnblogs.com/ztf20/p/11926815.html
Copyright © 2020-2023  润新知