Java創建和解析Json對象


最近工作遇到了 Json 解析的相關需求,整理下 JSONObject 相關操作。

文中使用的例子都是基於阿里巴巴的產品 FastJSON ,涉及到的包有:

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

 

下面列舉了開發過程中遇到過的一些常用操作:

(1) 創建 JSONObject

private static void createJSONObject() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", "Jason");
    jsonObject.put("id", 1);
    jsonObject.put("phone", "18271415782");
    System.out.println(jsonObject.toString());
}

 

(2) 創建 JSONArray

public static void createJsonArray() {
    JSONArray jsonarray = new JSONArray();

    JSONObject node = new JSONObject();
    node.put("name","kwang");
    node.put("age",20);
    jsonarray.add(node);

    node = new JSONObject();
    node.put("name","xkang");
    node.put("age",15);
    jsonarray.add(node);
    System.out.println(jsonarray);
}

 

(3) String 轉換為 JSONObject 對象

public static void StringToJson(String str) {
    JSONObject json = (JSONObject)JSONObject.parse(str);
    Iterator it = json.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        String value = String.valueOf(json.get(key));
        System.out.println(key + ":" + value);
    }
}

 

(4) JSONObject 轉換為 String

public static void JsonToSTring() {
    JSONObject json = new JSONObject();
    //向json中添加數據
    json.put("name", "kwang");
    json.put("height", 175);
    json.put("age", 24);

    //創建JSONArray數組,並將json添加到數組
    JSONArray array = new JSONArray();
    array.add(json);

    //轉換為字符串
    String jsonStr = array.toString();

    System.out.println(jsonStr);
}

 

【參考鏈接】

[1] feri, JAVA中的四種JSON解析方式詳解.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM