对JSON是在是第一次接触:.net解析JSON,收不到传递的数组
本帖最后由 wuhuanghao 于 2013-03-06 18:11:54 编辑 以下为传递的JSON方法:
var prsonjosn = { 'Id': '', 'Name': '','Title': '' };
prsonjosn.Id = mfi_id;
prsonjosn.Title = titleTemp; //title
prsonjosn.Name = mfi_name; //厂商名称
var jsonStr = "";
$.each(prsonjosn, function (i, n) {
jsonStr = jsonStr + """ + i + "":" + """ + n + "","
});
if (jsonStr == "") {
art.alert("失败");
return true;
}
jsonStr = jsonStr.substring(0, jsonStr.length - 1);
jsonStr = "{" + jsonStr + "}";
alert(jsonStr);//检测过,数据内容格式都正确的
$.post("AddOne.aspx?StrJson=" + { JsonStr: jsonStr },
public class YlObj
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Title { get; set; }
public YlObj(int Id_, string Name_, string Title_)
{
Id = Id_;
Name = Name_;
Title = Title_;
}
}
public class Json
{
public static string ToJsJson(object item)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
using(MemoryStream ms=new MemoryStream())
{
serializer.WriteObject(ms, item);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
}
//反序列化
public static T FromJsonTo<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
T jsonObject = (T)ser.ReadObject(ms);
return jsonObject;
}
}
}
string jsonStr = Request["JsonStr"];
List<YlObj> obj = Json.FromJsonTo<List<YlObj>>(jsonStr);
string i = string.Empty;
foreach (YlObj item in obj)
{
i = item.RMP_Title.ToString();
}
Response.Write("<script>alert('" + i + "');</script>");
Response.End();
AddOne.aspx?JsonStr={"Id":"0","Name":"其他","Title":"吉林"
string jsonStr = Request["JsonStr"];
//你的JSON字符串中没有含[ ]这样的json数组符合 可能无法反序列话成List
YlObj obj = Json.FromJsonTo<YlObj>(jsonStr);
string i = string.Empty;
i = obj.Title;
Response.Write("<script>alert('" + i + "');</script>");
Response.End();