Java JSONArray的封装与解析

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"):""));
        }
    }
}
原文地址:https://www.cnblogs.com/zhujiabin/p/9711999.html