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解析方式详解.

猜你喜欢

转载自www.cnblogs.com/walker-/p/10134249.html