. Net extracts multi-layer nested JSON and. net multi-layer nested json
Newtonsoft. Json. netbench DLL download please visit http://files.cnblogs.com/hualei/Newtonsoft.Json.Net20.rar
Extract such json from. net 2.0
{"Name": "lily", "age": 23, "addr": {"city": guangzhou, "province": guangdong }}
Reference namespace
Using Newtonsoft. Json;
Using Newtonsoft. Json. Linq;
You can regard the preceding JSON as an object. You only need to 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 parsing area as follows:
String jsonData = "{\" name \ ": \" lily \ ", \" age \ ": 23, \" addr \ ": {\" city \ ": guangzhou, \ "province \": guangdong }}";
UserInfo user = (UserInfo) JsonConvert. DeserializeObject (jsonData, typeof (UserInfo ));
The value of City is as long as: user. addr. City;
This can also be achieved
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 ();
Why is this json dynamic? For example, you can enter a json file, such as {"name": "lily", "age": 23, "addr": {"city": guangzhou, "province ": guangdong}; then let you enter an object, such as city, and then the system will output the guangzhou value. In this case, json is generated dynamically, I want to know if there is any way to read such json. (Note: json is multi-level nested .)
Just use Traversal
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;
}
When calling:
String jsonData = "{\" name \ ": \" lily \ ", \" age \ ": 23, \" addr \ ": {\" city \": \ "guangzhou \", \ "province \": \ "guangdong \"}}";
JObject jsonObj = JObject. Parse (jsonData );
Response. Write (GetJsonValue (jsonObj. Children (), "province "));
If multiple layers of nested arrays exist
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 to XML
String xmlstr = (XmlDocument) JsonConvert. DeserializeXmlNode (jsonData). InnerXml. ToString ();