標籤:des blog http java os io 檔案 資料
去: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;
}
}
}
}
轉自:http://cjl20082002.blog.163.com/blog/static/120827332009511103457637/