基本的JSONArray与JSONObject操作,还是挺简单的,但是自己鼓捣半天啊,把结果和代码记录下。
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
//待读取的JSON文件
String json="{'name':'xiaobai','school':[{'name1':'xiaoxue'},{'name1':'zhongxue'}]}";
//建立一个JSON对象
JSONObject jsonObject=JSONObject.fromObject(json);
//读取对象值,由键索引键值,
System.out.println(jsonObject.get("name"));
System.out.println(jsonObject.get("school"));
//System.out.println(jsonObject.get("school").toString());
//读取数组
JSONArray jsonArray=JSONArray.fromObject(jsonObject.get("school").toString());
//System.out.println(jsonArray.size());
//for循环读取数组里面的值
for(int i=0;i<jsonArray.size();i++){
JSONObject o=JSONObject.fromObject(jsonArray.get(i).toString());
System.out.println(o.get("name1"));
if(o.get("name1").equals("zhongxue")){
System.out.println("这是中学");
}
}
}
}
输出结果:
xiaobai
[{"name1":"xiaoxue"},{"name1":"zhongxue"}]
xiaoxue
zhongxue
这是中学
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Jsontest1 {
public static void main(String[] args) {
//待读取的JSON文件
String json1 = "{\"cat\":\"it\",//string类型\n" +
"\"languages\":[\n" +
"{\"id\":1,\"ide\":\"Eclipse\",\"name\":\"Java\"},\n" +
"{\"id\":2,\"ide\":\"XCode\",\"name\":\"Swift\"},\n" +
"{\"id\":3,\"ide\":\"Visual Studio\",\"name\":\"C#\"}\n" +
"],//整型\n" + "\"pop\":ture//布尔类型\n" + "}";
//建立一个JSON对象
JSONObject jsonObject1 = JSONObject.fromObject(json1);
//读取对象值,由键索引键值,
System.out.println(jsonObject1.get("cat"));
System.out.println(jsonObject1.get("pop"));
System.out.println(jsonObject1.get("languages"));
//读取数组
//for循环读取数组里面的值
JSONArray jsonArray1 = JSONArray.fromObject(jsonObject1.get("languages"));
if (jsonArray1.size() != 0) {
for (int i = 0; i < jsonArray1.size(); i++) {
System.out.println(jsonArray1.get(i));
String json2 = jsonArray1.get(i).toString();
JSONObject jsonObject2 = JSONObject.fromObject(json2);
System.out.println(jsonObject2.get("id"));
System.out.println(jsonObject2.get("ide"));
System.out.println(jsonObject2.get("name"));
}
}
}
}
运行结果:
it
ture
[{"id":1,"ide":"Eclipse","name":"Java"},{"id":2,"ide":"XCode","name":"Swift"},{"id":3,"ide":"Visual Studio","name":"C#"}]
{"id":1,"ide":"Eclipse","name":"Java"}
1
Eclipse
Java
{"id":2,"ide":"XCode","name":"Swift"}
2
XCode
Swift
{"id":3,"ide":"Visual Studio","name":"C#"}
3
Visual Studio
C#