자바 의 JSON 조작

2614 단어
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 list = new ArrayList();
         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);
    }
}

좋은 웹페이지 즐겨찾기