Java中的json數據類型操做

package com.ss1.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 JsonParse {

    public static void main(String[] args) throws JSONException {
         //接收到的JSON字符串
        String result = "[{\"username\" : \"yourname\",\"nickname\" : \"yournickname\"}]";
        //根據字符串生成JSON對象
        JSONArray json = new JSONArray(result);
        JSONObject resultJson = json.optJSONObject(0);
        
         //獲取數據項
        String username = resultJson.getString("username");
        System.out.println(username);
        
        
         String jsonStr = "{\"id\": 2," + 
                    " \"title\": \"json title\", " + 
                    "\"config\": {" +
                        "\"width\": 34," +
                        "\"height\": 35," +
                    "}, \"data\": [" +
                        "\"JAVA\", \"JavaScript\", \"PHP\"" +
                    "]}";
         
        //建立JSONObject對象
         JSONObject jsonObject = new JSONObject(jsonStr);
         System.out.println(jsonObject.getInt("id"));
         System.out.println(jsonObject.getString("title"));
         
         JSONObject config = jsonObject.getJSONObject("config");
         System.out.println(config.getInt("width"));
         
         //向json中添加數據
         JSONObject json1 = new JSONObject();
         json1.put("username", "cmy");
         json1.put("height", 172);
         json1.put("age", 23);
         
        //建立JSONArray數組,並將json添加到數組
         JSONArray jsonArray1 = new JSONArray();
         jsonArray1.put(json1);
        //轉換爲字符串
         System.out.println(jsonArray1.toString());
         
        //初始化ArrayList集合並添加數據
         List<String> list = new ArrayList<String>();
         list.add("username");
         list.add("age");
         list.add("sex");
         
        //初始化HashMap集合並添加數組
         Map map = new HashMap<>();
         map.put("bookname","css/html");
         map.put("price","42.0");
         
        //初始化JSONArray對象,並添加數據
         JSONArray array = new JSONArray();
         array.put(list);
         array.put(map);
         System.out.println(array);
    }
}
相關文章
相關標籤/搜索