json简单使用

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

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

public class test_main {

    static void parseJson() throws JSONException {
        String result = "[{"username": "your name", "user_json": {"username": "your name", "nickname": "your nickname"}}]";
        JSONArray resultArray = new JSONArray(result);
        JSONObject resultObj = resultArray.optJSONObject(0);

        String username = resultObj.getString("username");

        System.out.println(username);

        JSONObject user = resultObj.getJSONObject("user_json");
        String nickname = user.getString("nickname");
        System.out.println(nickname);

    }

    static void stringToJosn() throws JSONException {
        // 创建JSONObject对象
        JSONObject json = new JSONObject();

        // 向json中添加数据
        json.put("username", "wanglihong");
        json.put("height", 12.5);
        json.put("age", 24);

        // 创建JSONArray数组,并将json添加到数组
        JSONArray array = new JSONArray();
        array.put(json);

        // 转换为字符串
        String jsonStr = array.toString();

        System.out.println(jsonStr);

    }

    static void setToJosn() throws JSONException {
        // 初始化ArrayList集合并添加数据
        List<String> list = new ArrayList<String>();
        list.add("username");
        list.add("age");
        list.add("sex");

        // 初始化HashMap集合并添加数组
        Map map = new HashMap();
        map.put("bookname", "CSS3实战");
        map.put("price", 69.0);

        // 初始化JSONArray对象,并添加数据
        JSONArray array = new JSONArray();
        array.put(list);
        array.put(map);
        
        
        String jsonStr = array.toString();

        System.out.println(jsonStr);
        // 生成的JSON字符串为:[["username","age","sex"],{"price":69,"bookname":"CSS3实战"}]

    }

    public static void main(String[] args) throws JSONException {
        // TODO Auto-generated method stub

        // parseJson();

        // stringToJosn();
        setToJosn();
    }

}

 参考: http://www.cnblogs.com/undead/archive/2012/07/18/2594900.html

原文地址:https://www.cnblogs.com/huhuuu/p/4193230.html