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

  • 相关阅读:
    转:全面理解Javascript闭包和闭包的几种写法及用途
    VS2010 AnkhSvn
    silverlight 子UserControl获取父UserControl
    IIS相关
    (转)Javascript中console.log()用法
    (转)Sql Server 保留几位小数的两种做法
    asp.net Web API
    (转)C#中数组、ArrayList和List三者的区别
    PowerDesigner
    (转)jQuery.fn.extend与jQuery.extend到底区别在哪?
  • 原文地址:https://www.cnblogs.com/lemonu/p/10134249.html
Copyright © 2011-2022 走看看