JAVA中使用JSONArray和JSONObject

json

就是一个键对应一个值,简单的一对一关系。

JSONObject

 json对象,就是一个键对应一个值(键值对),使用的是大括号{ },如:{key:value}

JSONArray

 json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式的

  Json对象中添加的是键值对,JSONArray中添加的是Json对象

package blog;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONtest01 {
    public static void main(String[] args) {
        JSONArray array = new JSONArray();
        JSONObject jo = null;
        for(int i=0; i<10; i++) {
            jo = new JSONObject();
            jo.put(i, i+" "+"Json");
            array.add(jo);
        }
        System.out.println(array);
        for(Object j : array) {
            System.out.println(j);
        }
        
    }
}

运行结果:

[{"0":"0 Json"},{"1":"1 Json"},{"2":"2 Json"},{"3":"3 Json"},{"4":"4 Json"},{"5":"5 Json"},{"6":"6 Json"},{"7":"7 Json"},{"8":"8 Json"},{"9":"9 Json"}]
{"0":"0 Json"}
{"1":"1 Json"}
{"2":"2 Json"}
{"3":"3 Json"}
{"4":"4 Json"}
{"5":"5 Json"}
{"6":"6 Json"}
{"7":"7 Json"}
{"8":"8 Json"}
{"9":"9 Json"}

 

需要引入的包:

json-lib-2.2.3-jdk15.jar 

commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-collections.jar
commons-httpclient-3.0.1.jar
commons-lang-2.4.jar
commons-logging-1.0.4.jar
ezmorph-1.0.3.jar

猜你喜欢

转载自www.cnblogs.com/dong973711/p/10749411.html