Newtonsoft.Json.Net20.dll download please visit http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar
Such extraction of json in .net 2.0
{"name":"lily","age":23,"addr":{"city":guangzhou,"province":guangdong}}
Namespace references
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
The above can be seen as a JSON object. You can just write the corresponding class
public class UserInfo
{
public string name;
public int age;
public address addr;
}
public class address
{
public string city;
public string province;
}
Then write in the place resolved:
string jsonData="{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":guangzhou,\"province\":guangdong}}";
UserInfo user=(UserInfo)JsonConvert.DeserializeObject(jsonData, typeof(UserInfo));
As long as the value obtained City: user.addr.City;
Such realization is also OK
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();
How does this json is dynamic it? For example lets you enter a JSON, such as { "name": "lily", "age": 23, "addr": { "city": guangzhou, "province": guangdong}}; then let you enter an object, such as city, guangzhou then the system will output this value, that this is the case, json is dynamically generated, I would like to know there is no way to read such json. (Note, json is a multi-level nested.)
It is used to traverse
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;
}
In the time of the call:
string jsonData = "{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":\"guangzhou\",\"province\":\"guangdong\"}}";
JObject jsonObj = JObject.Parse(jsonData);
Response.Write(GetJsonValue(jsonObj.Children(), "province"));
If there are nested arrays
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();