溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

數(shù)據(jù)轉換為json格式

發(fā)布時間:2020-07-14 22:15:27 來源:網(wǎng)絡 閱讀:1251 作者:101ttyy 欄目:開發(fā)技術

一.使用Gson轉換為json格式
依賴的maven包:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.4</version>
</dependency>

關鍵代碼如下:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
//....
Gson gson = new GsonBuilder().create();
        gson.toJson("Hello", System.out);
        gson.toJson(123, System.out);
        System.out.println();
        JsonObject json = new JsonObject();
        json.addProperty("dd", "22");
        json.addProperty("dds", 22);
        System.out.println(json);

輸出:

"Hello"123

{"dd":"22","dds":22}


第二 .使用Json-lib轉換json格式

Json-lib 是一個 Java 類庫(官網(wǎng):http://json-lib.sourceforge.net/)可以實現(xiàn)如下功能:

 .轉換 javabeans, maps, collections, java arrays 和 XML 成為 json 格式數(shù)據(jù)

 .轉換 json 格式數(shù)據(jù)成為 javabeans 對象

Json-lib 需要的 jar 包

  • commons-beanutils-1.8.3.jar

  • commons-collections-3.2.1.jar

  • commons-lang-2.6.jar

  • commons-logging-1.1.1.jar

  • ezmorph-1.0.6.jar

  • json-lib-2.4-jdk15.jar

Json-lib 的使用

1. 將 Array 解析成 Json 串。使用 JSONArray 可以解析 Array 類型:

package util.copy;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class test {
    public static void main(String[] args) {
        JSONObject json2 = new JSONObject();
        json2.put("ss", "55");
        System.out.println(json2);
        //將 Array 解析成 Json 串
       String[] str = { "Jack", "Tom", "90", "true" };
       JSONArray json = JSONArray.fromObject(str);
       System.err.println(json);
       
       //對像數(shù)組,注意數(shù)字和布而值
       Object[] o = { "北京", "上海", 89, true, 90.87 };
       json = JSONArray.fromObject(o);
       System.err.println(json);

       //使用集合類
       List<String> list = new ArrayList<String>();
       list.add("Jack");
       list.add("Rose");
       json = JSONArray.fromObject(list);
       System.err.println(json);

       //使用 set 集
       Set<Object> set = new HashSet<Object>();
       set.add("Hello");
       set.add(true);
       set.add(99);
       json = JSONArray.fromObject(set);
       System.err.println(json);
    }
}

運行結果如下:

{"ss":"55"}
["Jack","Tom","90","true"]
["北京","上海",89,true,90.87]
["Jack","Rose"]
[99,true,"Hello"]


2. 將 JavaBean/Map 解析成 JSON 串。 使用JSONObject 解析:

public static void main(String[] args) {
            //解析 HashMap
           Map<String, Object> map = new HashMap<String, Object>();
           map.put("name", "Tom");
           map.put("age", 33);
           JSONObject jsonObject = JSONObject.fromObject(map);
           System.out.println(jsonObject);
           
           //解析 JavaBean
           Person person = new Person("A001", "Jack");
           jsonObject = jsonObject.fromObject(person);
           System.out.println(jsonObject);
           
           //解析嵌套的對象
           map.put("person", person);
           jsonObject = jsonObject.fromObject(map);
           System.out.println(jsonObject);
    }

運行結果如下:

{"age":33,"name":"Tom"}
{"id":"A001","name":"Jack"}
{"person":{"id":"A001","name":"Jack"},"age":33,"name":"Tom"}


3. 使用 JsonConfig 過慮屬性:適用于 JavaBean/Map

public static void main(String[] args) {
       JsonConfig config = new JsonConfig();
       config.setExcludes(new String[] { "name" });  // 指定在轉換時不包含哪些屬性
       Person person = new Person("A001", "Jack");
       JSONObject jsonObject = JSONObject.fromObject(person, config); // 在轉換時傳入之前的配置對象       System.out.println(jsonObject);
   }

運行結果如下,在運行結果中我們可以看到 name 屬性被過濾掉了:

{"id":"A001"}


4. 將 Json 串轉換成 Array:

public static void main(String[] args) {
       JSONArray jsonArray = JSONArray.fromObject("[89,90,99]");
       Object array = JSONArray.toArray(jsonArray);
       System.out.println(array);
       System.out.println(Arrays.asList((Object[]) array));
   }


運行結果如下:

[Ljava.lang.Object;@1e5003f6
[89, 90, 99]


5. 將 Json 串轉成 JavaBean/Map:

public static void main(String[] args) {
            //將 Json 形式的字符串轉換為 Map
            String str = "{\"name\":\"Tom\",\"age\":90}";
           JSONObject jsonObject = JSONObject.fromObject(str);
           Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
           System.out.println(map);
           
           //將 Json 形式的字符串轉換為 JavaBean
           str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
           jsonObject = JSONObject.fromObject(str);
           System.out.println(jsonObject);
           Person person = (Person) JSONObject.toBean(jsonObject, Person.class);
           System.out.println(person);
    }

運行結果如下:

{age=90, name=Tom}
Person [id=A001, name=Jack]


在將 Json 形式的字符串轉換為 JavaBean 的時候需要注意 JavaBean 中必須有無參構造函數(shù),否則會報如下找不到初始化方法的錯誤:

Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at net.sf.json.JSONObject.toBean(JSONObject.java:288)
   at net.sf.json.JSONObject.toBean(JSONObject.java:233)
   at cn.sunzn.json.JsonLib.main(JsonLib.java:23)
Caused by: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at java.lang.Class.getConstructor0(Unknown Source)
   at java.lang.Class.getDeclaredConstructor(Unknown Source)
   at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
   at net.sf.json.JSONObject.toBean(JSONObject.java:282)
   ... 2 more




向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI