• 使用Java创建JSON数据


    --------------siwuxie095

       

       

       

       

       

       

       

    工程名:TestCreateJSON

    包名:com.siwuxie095.json

    类名:CreateJSON.java

       

       

    打开资源管理器,在工程 TestCreateJSON 文件夹下,创建一个

    文件夹:lib,在其中放入:gson-2.8.0.jar

       

       

    截止 2017/3/30 最新版本 gson-2.8.0 下载链接:

    http://download.csdn.net/detail/siwuxie095/9799544

       

       

       

    工程结构目录如下:

       

       

       

       

    选择 gson-2.8.0.jar,右键->Build Path->Add to Build Path

       

    此时,工程结构目录一览:

       

       

       

       

       

       

    代码:

       

    package com.siwuxie095.json;

       

    import com.google.gson.JsonArray;

    import com.google.gson.JsonObject;

       

    public class CreateJSON {

       

    public static void main(String[] args) {

    //要创建JSON格式的数据,首先要创建一个整体的JSON的对象,作为一个容器

    JsonObject object=new JsonObject();

     

    //如果要为当前的JSON对象添加另一个JSON对象,使用add()方法

    //如果要为当前的JSON对象添加属性值(键值对),使用addProperty()方法

    object.addProperty("category", "it");

     

    //接下来构建JSON数组,名称是 languages

    JsonArray array=new JsonArray();

     

    JsonObject lan1=new JsonObject();

    lan1.addProperty("id", 1);

    lan1.addProperty("name", "Java");

    lan1.addProperty("ide", "Eclipse");

    // lan1 添加到 array

    array.add(lan1);

     

    JsonObject lan2=new JsonObject();

    lan2.addProperty("id", 2);

    lan2.addProperty("name", "Swift");

    lan2.addProperty("ide", "Xcode");

    // lan2 添加到 array

    array.add(lan2);

     

    JsonObject lan3=new JsonObject();

    lan3.addProperty("id", 3);

    lan3.addProperty("name", "C#");

    lan3.addProperty("ide", "Visual Studio");

    // lan3 添加到 array

    array.add(lan3);

     

     

    // array 添加到 object,指定 array 的名称: languages(键)

    object.add("languages", array);

     

    //添加最后一个属性:pop

    object.addProperty("pop", true);

     

     

    //创建完毕,转换成字符串

    System.out.println(object.toString());

     

     

    }

       

    }

       

       

    运行一览:

       

       

       

       

    将输出的 JSON 数据,复制->粘贴->格式化:

       

       

       

       

       

       

       

    【made by siwuxie095】

  • 相关阅读:
    Catharanthus roseus(长春花碱)的生物合成
    论文好句积累
    C# OpenFileDialog用法
    JAVA配置环境变量的意义
    如何为织梦表单添加时间
    winform开发基础
    tomcat中jsp编译
    垂直居中——父元素高度确定的单行文本、父元素高度确定的多行文本
    水平居中——行内元素、定宽块、不定宽块
    批处理文件
  • 原文地址:https://www.cnblogs.com/siwuxie095/p/6649379.html
Copyright © 2020-2023  润新知