1. 程式人生 > >JAVA中使用JSONArray和JSONObject

JAVA中使用JSONArray和JSONObject

port ack i++ 大括號 ttpClient 一對一 pri 對象 arr

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

JAVA中使用JSONArray和JSONObject