使用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】

原文地址:https://www.cnblogs.com/siwuxie095/p/6649379.html