.net(c#)提取多层嵌套的JSON

Newtonsoft.Json.Net20.dll 下载请访问https://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();

posted @ 2013-07-23 15:21  Raywang80s  阅读(597)  评论(0编辑  收藏  举报