码迷,mamicode.com
首页 > 其他好文 > 详细

键值对解析

时间:2019-11-25 13:47:50      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:stream   result   indexof   字节   index   read   length   符号   数组   

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

 

键值对解析

标签:stream   result   indexof   字节   index   read   length   符号   数组   

原文地址:https://www.cnblogs.com/ztf20/p/11926815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!