http://cjl20082002.blog.163.com/blog/static/120827332009511103457637/
去:http://json.codeplex.com/下载 Json.NET 1.3.1(.net2.0用)
Json.net API:http://james.newtonking.com/projects/json/help/
解压吧BIN文件拷贝到项目的BIN文件中(我就考那Newtonsoft.Json.dll 配置的xml文件没拷还没知道这么用)
反序列化:(就是把JSON取出来赋予C#然后操作数据 我是这样理解的)
代码:
using Newtonsoft.Json;//导入类
string ojson = "[{SZD:'BM',SGX:'=',SZ:'33'},{SZD:'SJ',SGX:'=',SZ:'3333'},{SZD:'SJ',SGX:'=',SZ:'3333'}]";
/*获取json*/
Newtonsoft.Json.JavaScriptArray jsa = (JavaScriptArray)JavaScriptConvert.DeserializeObject(ojson);
for (int i = 0; i < jsa.Count; i++)
{
JavaScriptObject jso = (JavaScriptObject)jsa[i];
/*JavaScriptObject[""] 获取具体的值*/
Response.Write(jso["SZD"].ToString()+jso["SGX"].ToString()+Convert.ToInt32(jso["SZ"])+"</br>");
}
目标:以C#解析一串类似[{},{},{}]承载着数组数据的json字符串。将其反序列化为一个对象列表
运行环境:
NUnit2.4 C# .net2.0
代码:
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json;
namespace TestPrj
{
[TestFixture]
public class TestJson
{
[Test]
public void testA()
{
//测试数据
string ojson = "[{SZD:'BM',SGX:'=',SZ:'33'},{SZD:'SJ',SGX:'=',SZ:'3333'},{SZD:'SJ',SGX:'=',SZ:'3333'}]";
Newtonsoft.Json.JavaScriptArray jsa = (JavaScriptArray)JavaScriptConvert.DeserializeObject(ojson);
IList<searchArgs> li = new List<searchArgs>();
for (int i = 0; i < jsa.Count; i++)
{
JavaScriptObject jso = (JavaScriptObject)jsa[i];
searchArgs sa = new searchArgs(GetJsonStringValue(jso, "SZD"), GetJsonStringValue(jso, "SGX"), GetJsonStringValue(jso, "SZ"));
li.Add(sa);
}
System.Console.WriteLine(li.Count);
}
public class searchArgs {
public string SZD { get; set; }
public string SGX { get; set; }
public string SZ { get; set; }
public searchArgs(string szd,string sgx,string sz) {
SZD = szd;
SGX = sgx;
SZ = sz;
}
}
public static string GetJsonStringValue(Newtonsoft.Json.JavaScriptObject jso, string key)
{
try
{
return jso[key] == null ? string.Empty : jso[key].ToString();
}
catch (Exception e)
{
return string.Empty;
}
}
}
}