要使用.NET自带的JSON处理工具需要引用下面的命名空间:
using System.Web.Script.Serialization;
1.编码
myConfig mc = new myConfig();
mc.config = "测试";
mc.info = "还不错"; JavaScriptSerializer json = new JavaScriptSerializer();
object result = json.Serialize(mc);
Response.Write(result);
2.解码
// 自定义类 下面会用到
public class myConfig
{
public string config { get; set; }
public string info { get; set; }
}
1>. 简单的解码
string str = "{config:'最新发动机',info:'我觉得是最好的'}"; JavaScriptSerializer json = new JavaScriptSerializer();
myConfig mc = json.Deserialize<myConfig>(str); Response.Write(mc.config + "--" + mc.info);
2>. 复杂的解码
string str = "[{config:'发动机',info:'最好的'},{config:'排量',info:'2.5cc'}]"; JavaScriptSerializer json = new JavaScriptSerializer();
// List<myConfig> result = (List<myConfig>)json.Deserialize<List<myConfig>>(str);
// 功能同上
List<myConfig> result = (List<myConfig>)json.Deserialize(str, typeof(List<myConfig>)); foreach (var item in result)
{
Response.Write(item.config + "--" + item.info + "<br/>");
}