1、问题描述
json是网络传输数据的一直常用格式,在写接口的时候,会用json传递数据来测试接口。
2、封装和解析
package com.kigang.test;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.Iterator;
/**
* @author qqg
* @description jsonArray测试
* @date 2018/1/24
*/
public class JSONArrayTest {
public static void main(String[] args) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("userId","15032");
object.put("topTitle","标题");
object.put("topContent","内容");
JSONObject object1 = new JSONObject();
object1.put("userId","15032");
object1.put("topTitle","标题");
array.add(object);
array.add(object1);
System.out.println("array:"+array.toString());
Iterator<Object> it = array.iterator();
while(it.hasNext()){
JSONObject object2 = (JSONObject) it.next();
//先判断key是否存在,在取值;直接取值可能会空指针异常
System.out.println("userId:"+(object2.has("userId")?object2.get("userId"):"空"));
System.out.println("topTitle:"+(object2.has("topTitle")?object2.get("topTitle"):"空"));
System.out.println("topContent:"+(object2.has("topContent")?object2.get("topContent"):"空"));
}
}
}