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"):""));
        }
    }
}

 

posted @ 2018-09-27 11:04  星辰之力  阅读(740)  评论(0编辑  收藏  举报