位置:首页 » 文章/教程分享 » Java使用org.json.jar构造和解析Json数据
org.json是Java常用的Json解析工具,主要提供JSONObject和JSONArray类.和其他解析工具相比要轻量的多只需要导入org,json的jar包即可,不用依赖其他的jar包。其他不同之处在这里不做介绍了

解析案例以及代码案例

解析json对象

package test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class ReadJson {
    // 简单的json测试字符串
    public static final  String JSON_SIMPLE = "{'name':'tom','age':16}";
    //嵌套的json测试字符串
    public static final String JSON_MULTI = "{'name':'tom','score':{'Math':98,'English':90}}";
    public static void main(String [] args){
        printSimple();
        printMulit();
    }

    //解析json数据
    public static Map<String, String> toMap(String jsonString) throws JSONException  {  

        JSONObject jsonObject = new JSONObject(jsonString);  

        Map<String, String> result = new HashMap<String, String>();  
        Iterator<?> iterator = jsonObject.keys();  
        String key = null;  
        String value = null;  

        while (iterator.hasNext()) {  

            key = (String) iterator.next();  
            value = jsonObject.getString(key);  
            result.put(key, value);  

        }  
        return result;  
    }  

   //输出简单的json格式数据
    public static  void printSimple(){ 
        String jsonString=JSON_SIMPLE;
        Map<String, String> map=null;
        try {
            map=toMap(jsonString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String name=map.get("name");
        String age=map.get("age");
        System.out.println(name+"------"+age);
    }
    //输出嵌套的json格式出去
    public static void printMulit(){
        String jsonString=JSON_MULTI;
        Map<String, String> map=null;
        Map<String, String> map1=null;
        try {
            map=toMap(jsonString);
            String name=map.get("name");
            String score=map.get("score");
            map1=toMap(score);
            String Math=map1.get("Math");
            String English=map1.get("English");
            System.out.println(name+"-"+Math+"-"+English);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

解析json数组

package test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ReadJson2 {
    //json字符串
    static String JsonStr = "{object:{persons:" +
            "[{name:'呵呵',image:'http://10.0.159.132:8080/Web/s1.png'}," +
            "{name:'哈哈',image:'http://10.0.159.132:8080/Web/s1.png'}," +
            "{name:'嘿嘿',image:'http://10.0.159.132:8080/Web/s2.jpg'}]}}";
    public static void main(String []args) throws JSONException{
        List<Person> list=jsonStrToList(JsonStr);
        Iterator<Person> it = list.iterator();
        while(it.hasNext()){
            Person p = (Person) it.next();
            System.out.println(p.getName()+"--"+p.getImage());
        }
    }

    /**
     * 解析json数组中的jsonObject
     * @param jsonStr
     * @return
     * @throws JSONException
     */
    public static List<Person> jsonStrToList(String jsonStr) throws JSONException{
        List<Person> list=new ArrayList<Person>();

        //通过字符串,获得最外部的json对象
        JSONObject jsonObj=new JSONObject(jsonStr);
        //通过属性名,获得内部的对象
        JSONObject jsonPersons=jsonObj.getJSONObject("object");
        //获得json对象组
        JSONArray arr=jsonPersons.getJSONArray("persons");
        for(int i=0;i<arr.length();i++){
            //循环对象,并通过getString("属性名");来获得值
            JSONObject tempJson=arr.getJSONObject(i);
            Person person=new Person();

            person.setName(tempJson.getString("name"));
            person.setImage(tempJson.getString("image"));
            list.add(person);
        }
        return list;

    }
}

构造案例及代码


JSONObject的构造json

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class writeJson {
    public static void constructorTest() throws JSONException {

        String jsonStr = "{'name':'JTZen9','age':21}";
        JSONObject strJson;

        // 传入字符串
        strJson = new JSONObject(jsonStr);
        System.out.println("构造参数为String类:" + strJson);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("age", 21);
        map.put("sex", "male");
        map.put("name", "JTZen9");
        JSONObject mapJson = new JSONObject(map); // 传入Map类型
        System.out.println("构造参数为Map类:" + mapJson);

        Student student = new Student();
        student.setAge(21);
        student.setName("JTZen9");
        student.setSex("male");
        JSONObject beanJson = new JSONObject(student); // 传入Bean类型
        System.out.println("构造参数为Bean类:" + beanJson);
    }  

        public static void putMethodTest() throws JSONException {  

            JSONObject jsonObject1 = new JSONObject();  
            jsonObject1.put("bookName", "JTZen9");  
            jsonObject1.put("age", 21);  
            System.out.println(jsonObject1);  

            JSONObject jsonObject2 = new JSONObject();  
            List<Object> list = new ArrayList<Object>();  
            for (int i = 1; i < 3; i++) {  
                Map<String , Object> map = new HashMap<String ,Object>();  
                map.put("title", "java程序设计 第" + i + "版");  
                map.put("price", i*20);  
                list.add(map);  
            }  
            jsonObject2.put("book", list);  
            System.out.println(jsonObject2);  

            Student student = new Student();  
            student.setAge(21);  
            student.setName("JTZen9");  
            student.setSex("male");  
            jsonObject2 = new JSONObject(student);  
            JSONObject jsonObject3 = new JSONObject();  
            jsonObject3.put("people", jsonObject2);   //不可以直接传bean类对象put("people",student)  
            System.out.println(jsonObject3);  
        }  

        public static void main(String[] args) throws Exception {  
            constructorTest();  
            System.out.println("---------------------------------------------------------");  
            putMethodTest();  
        }   
}

JSONArray构造json

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;

public class JsonArrayTest {
    public static void constructorTest() throws JSONException {  

        String jsonStr = "[{'name':'JTZen9','age':21}]";  
        JSONArray strJson = new JSONArray(jsonStr);     // 传入字符串  
        System.out.println("构造参数为String类:" + strJson);  

        List<Object> list = new ArrayList<Object>();  
        for (int i = 1; i < 3; i++) {  
            Map<String ,Object> map = new HashMap<String, Object>();  
            map.put("title", "java程序设计 第" + i + "版");  
            map.put("price", i*20);  
            list.add(map);  
        }  
        JSONArray mapJson = new JSONArray(list);        // 传入Collection类型  
        System.out.println("构造参数为Collection类:" + mapJson);  

        int[] numlist = new int[10];  
        for (int i = 0; i < numlist.length; i++) {  
            numlist[i] = i;  
        }  
        JSONArray arrayJson = new JSONArray(numlist);   // 传入Array类型,实例1  
        System.out.println(arrayJson);  

        Student[] student = {new Student(),new Student()};  
        student[0].setAge(21);  
        student[0].setName("JTZen9");  
        student[0].setSex("male");  
        student[1].setAge(21);  
        student[1].setName("heiheihei");  
        student[1].setSex("female");  
        JSONArray beanJson = new JSONArray(student);    // 传入Array类型,实例2  
        System.out.println("构造参数为Array类:" + beanJson);  
    }  

     public static void putMethodTest() throws JSONException {  
            JSONArray jsonArray1 = new JSONArray();  
            jsonArray1.put("JTZen9");  
            jsonArray1.put(21);  
            jsonArray1.put("male");  
            System.out.println(jsonArray1);  

            JSONArray jsonArray2 = new JSONArray();  
            Map<String ,Object> map = new HashMap<String ,Object>();  
            map.put("title", "java程序设计 第2版");  
            map.put("price", 20);  
            jsonArray2.put(map);        //传入一个map  
            System.out.println("传入一个Map:" + jsonArray2);  
            map.clear();  
            map.put("title", "java程序设计 第3版");  
            map.put("price", 30);  
            jsonArray2.put(map);        //没有下标的直接在结果后面添加  
            System.out.println("没有指定下标:" + jsonArray2);  
            map.clear();  
            map.put("title", "java程序设计 第1版");  
            map.put("price", 10);  
            jsonArray2.put(0,map);      //使用下标可以添加到自定义的位置  
            System.out.println("添加到第一个位置:" + jsonArray2);  

            Student[] student = { new Student(), new Student() };  
            student[0].setAge(21);  
            student[0].setName("JTZen9");  
            student[0].setSex("male");  
            student[1].setAge(21);  
            student[1].setName("heiheihei");  
            student[1].setSex("female");  
            JSONArray jsonArray3 = new JSONArray();   
            jsonArray3.put(student);  
            System.out.println("注意输出结果:" + jsonArray3);  

        }  
    public static void main(String[] args) throws JSONException {  
        constructorTest();  
        System.out.println("-------------------------------------------------");
        putMethodTest();
    }  
}