zoukankan      html  css  js  c++  java
  • 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解析方式详解.

  • 相关阅读:
    event.target.tagName
    Web安全之跨站伪造请求(CSRF)
    Web安全之XSS 入门与介绍
    Web安全之Web 安全介绍与基础入门知识
    设计模式之命令模式
    前端常用的库和实用技术之JavaScript多线程
    前端常用的库和实用技术之JavaScript面向切面编程
    设计模式之职责链模式
    设计模式之适配器模式
    设计模式之策略模式
  • 原文地址:https://www.cnblogs.com/lemonu/p/10134249.html
Copyright © 2011-2022 走看看