將字典型別(Dictionary)型別資料序列化為json資料及拼接為key1=value1&key2=value2的兩種方法
阿新 • • 發佈:2019-01-27
一、序列化為Json字串
當需要將物件轉為{ "street": "科技園路.", "city": "江蘇蘇州", "country": "中國"}
這種格式時使用序列化(不引入外部dll的方式)
public static String SerializeObject(Object o)
{
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
String jsonString = json.Serialize (o);
return jsonString;
}
在使用上述方法之前先得新增引用“System.Web.Extensions”,然後還得在類前面增加using System.Web;
反序列化為指定物件
JavaScriptSerializer js = new JavaScriptSerializer();
Student model = js.Deserialize< Student>(jsonStr);// //反序列化
二、將字串key、value進行&連線
兩個方法大同小異
方法一:
private string dataToString(Dictionary<string,string> data)
{
StringBuilder sub = new StringBuilder();
foreach (string s in data.Keys)
{
if (sub.Length > 0)
{
sub.Append("&");
}
sub.Append(System.Web.HttpUtility.UrlEncode(s) + "=" + System.Web.HttpUtility.UrlEncode(data[s].ToString()));
}
return sub.ToString();
}
方法2:
private string dataToString(Dictionary<string,string> data)
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in data.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, data[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, data[key]);
}
i++;
}
return buffer.ToString();
}
執行結果
ps,遇到的bug:
解決方法: