package com.test.demo.xmljson;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
*
* @author
* json格式取数据
*/
public class JsonFormatCls {
/**
* 获取json数据
* 以“{”开头的是对象格式获取时用 getJSONObject()
* 以“[”开头的是数组格式获取时用getJSONArray()
*
*/
public static void getJsonData(){
String jsonData="{\"test\":{\"scholl\":{\"schollitem\":{\"name\":\"神州希望小学\",\"phone\":\"68686868\",\"address\":\"XXX省XXX市XXX县\"},\"sclass\":{\"-stype\":\"一级部\",\"classitem\":[{\"teacher\":\"Z老师\",\"classname\":\"一年级\",\"studentnum\":\"30\"},{\"teacher\":\"Y老师\",\"classname\":\"二年级\",\"studentnum\":\"35\"},{\"teacher\":\"J老师\",\"classname\":\"三年级\",\"studentnum\":\"39\"},{\"teacher\":\"H老师\",\"classname\":\"四年级\",\"studentnum\":\"30\"}]}}}}";
JSONObject obj= JSONObject.fromObject(jsonData);
System.out.println("obj"+"-----"+obj);
JSONObject schollObj=obj.getJSONObject("test").getJSONObject("scholl");
System.out.println("testObj"+"------"+schollObj);
if(schollObj.toString().length()>0){//判断是否包含该节点
JSONObject schollitem=schollObj.getJSONObject("schollitem");
System.out.println("schollitem"+"------"+schollitem);
String name=schollitem.get("name").toString();
String phone=schollitem.get("phone").toString();
String address=schollitem.get("address").toString();
System.out.println("name"+name+"----phone-----"+phone+"----address----"+address);
JSONObject jsonClass= schollObj.getJSONObject("sclass");
System.out.println("scalss-----"+jsonClass);
String type=jsonClass.get("-stype").toString();
System.out.println("jsonClass"+jsonClass+"----type-----"+type);
final char[] strChar = jsonClass.get("classitem").toString().substring(0, 1).toCharArray(); //获取classitem内容首字符
final char firstChar = strChar[0];
//此处判断获取的内容的首字符是"["还是"{",如果是"["用getJSONArray()获取节点,如果是“{”用getJSONObject()获取。
if(firstChar=='['){
JSONArray classitemArray= jsonClass.getJSONArray("classitem");
for (int i = 0; i < classitemArray.size(); i++) {
String teacher=classitemArray.getJSONObject(i).get("teacher").toString();
String classname=classitemArray.getJSONObject(i).get("classname").toString();
String studentnum=classitemArray.getJSONObject(i).get("studentnum").toString();
System.out.println("teacher:"+teacher+"---"+"classname:"+classname+"----studentnum:"+studentnum);
}
}else if(firstChar=='{'){
JSONObject classitemObject= jsonClass.getJSONObject("classitem");
String teacher=classitemObject.get("teacher").toString();
String classname=classitemObject.get("classname").toString();
String studentnum=classitemObject.get("studentnum").toString();
System.out.println("teacher:"+teacher+"---"+"classname:"+classname+"----studentnum:"+studentnum);
}
}
}
public static void main(String [] args){
getJsonData();
}
}