Newtonsoft.Json.Net20.dll 下載請訪問http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar 在.net 2.0中提取這樣的json {"name":"lily","age":23,"addr":{"city":gu ...
Newtonsoft.Json.Net20.dll 下載請訪問http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar
在.net 2.0中提取這樣的json
{"name":"lily","age":23,"addr":{"city":guangzhou,"province":guangdong}}
引用命名空間
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
可以把上面的JSON看成一個對象.你只要寫對應的類即可
public class UserInfo
{
public string name;
public int age;
public address addr;
}
public class address
{
public string city;
public string province;
}
然後在解析的地方這樣寫:
string jsonData="{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":guangzhou,\"province\":guangdong}}";
UserInfo user=(UserInfo)JsonConvert.DeserializeObject(jsonData, typeof(UserInfo));
得到City的值只要:user.addr.City;
這樣實現也行
JObject jsonObj = JObject.Parse(jsonData);
string name=jsonObj ["name"].ToString();
string age=jsonObj ["age"].ToString();
string city=((JObject )jsonObj ["addr"])["city"].ToString();
string province=((JObject )jsonObj ["addr"])["province"].ToString();
如 何這個json是動態的呢?譬如讓你輸入一個json,如{"name":"lily","age":23,"addr": {"city":guangzhou,"province":guangdong}}; 然後讓你輸入一個對象,如city,然後系統會輸出guangzhou這個值,那這樣的話,json就是動態生成的了,我想瞭解有沒有讀取這樣的json 的方法。(註意,json是多級嵌套的。)
就用遍歷
public string GetJsonValue(JEnumerable<JToken> jToken,string key)
{
IEnumerator enumerator = jToken.GetEnumerator();
while (enumerator.MoveNext())
{
JToken jc = (JToken)enumerator.Current;
if (jc is JObject||((JProperty)jc).Value is JObject)
{
return GetJsonValue(jc.Children(), key);
}
else
{
if (((JProperty)jc).Name == key)
{
return ((JProperty)jc).Value.ToString();
}
}
}
return null;
}
在調用的時候:
string jsonData = "{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":\"guangzhou\",\"province\":\"guangdong\"}}";
JObject jsonObj = JObject.Parse(jsonData);
Response.Write(GetJsonValue(jsonObj.Children(), "province"));
如果有多層嵌套的數組
string jsonData = "{\"addr\":[{\"city\":\"guangzhou\",\"province\":\"guangdong\"},{\"city\":\"guiyang\",\"province\":\"guizhou\"}]}";
JObject jsonObj = JObject.Parse(jsonData);
JArray jar = JArray.Parse(jsonObj["addr"].ToString());
JObject j = JObject.Parse(jar[0].ToString());
Response.Write(j["city"]);
JSON轉XML
string xmlstr=((XmlDocument)JsonConvert.DeserializeXmlNode(jsonData)).InnerXml.ToString();