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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM