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);
    }
}

 

posted @ 2016-08-10 17:19  公众号java-codestack  阅读(9994)  评论(0编辑  收藏  举报