Json數(shù)據(jù)解析與轉(zhuǎn)換 -- Java使用示例
概要
json是前后臺交互常用的數(shù)據(jù)格式,在java后臺中經(jīng)常需要實現(xiàn)java bean、list和json字符串的相互轉(zhuǎn)化,故簡單介紹不同框架的使用,提供簡單工具類。
在Java中,常見的json框架有:Jackson(springboot默認)、fastjson(阿里開源)、Gson(谷歌開源)。網(wǎng)絡(luò)有它們的性能對比研究,此處不做討論,根據(jù)自己習(xí)慣來選擇即可。
json的數(shù)據(jù)結(jié)構(gòu)包括:{}、[],等同于java的對象、數(shù)組。兩者相互組合,就能夠表達很復(fù)雜的數(shù)據(jù)結(jié)構(gòu)了。
使用
Fastjon
- 添加Maven依賴,可從https://github.com/alibaba/fastjson獲取。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.61</version>
</dependency>
- 使用示例,主要對象是 JSON、JSONArray、JSONObject
public void fastJsonTest() {
//數(shù)據(jù)示例
List list = Arrays.asList("Banana","apple","Orange");
String obj = "{\"id\":1001,\"age\":12}";
Person p = new Person(1001,12,"David");
//java對象 ==> json字符串,json對象
String str = JSON.toJSONString(p);
JSONObject jsonObj1 = (JSONObject) JSON.toJSON(p);
//json字符串 ==> json對象、Java對象
Person p1 = JSON.parseObject(obj, Person.class);
JSONObject jsonObj2 = JSON.parseObject(obj);
//json對象 ==> java對象
Person p2 = JSON.toJavaObject(jsonObj2, Person.class);
//數(shù)組處理
JSONArray json = (JSONArray)JSON.toJSON(list);
String jsonStr = String.valueOf(JSON.toJSON(json));
}
Jackson
- 添加Maven依賴,SpringBoot中默認引入,無需額外操作。包括三個jar包:jackson-databind、jackson-core、jackson-annotations
- 使用示例,注意異常處理
public void jacksonDemo() throws IOException {
//數(shù)據(jù)示例
User user = new User("001","David","xxx",12);
Map<String,Object> map = new HashMap<String,Object>();
map.put("A1", user);
map.put("A2", new ArrayList<String>());
//創(chuàng)建ObjectMapper對象
ObjectMapper mapper = new ObjectMapper();
//Java對象 ==> json字符串
String jsonStr1 = mapper.writeValueAsString(user);
String jsonStr2 = mapper.writeValueAsString(map);
//json字符串 ==> Java對象
User u = mapper.readValue(jsonStr1, User.class);
Map m = mapper.readValue(jsonStr2, Map.class);
}
Gson
-
添加Maven依賴,可從 https://github.com/google/gson 獲取
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.7</version> </dependency> -
使用示例
public void gsonDemo() { //示例數(shù)據(jù) User user = new User("kevin",22,new Date(),Arrays.asList("aa","bb","cc")); List list = Arrays.asList("Banana","apple","Orange"); //創(chuàng)建gson對象 Gson gson = new Gson(); //Java對象 ==> json字符串 String s1 = gson.toJson(list); String s2 = gson.toJson(user); //json字符串 ==> Java對象 gson.fromJson(s1, List.class); gson.fromJson(s2, User.class); }
分類: 工具使用
[好文要頂](javascript:void(0);) [關(guān)注我](javascript:void(0);) [收藏該文](javascript:void(0);) [
image

image
好大的風(fēng)
關(guān)注 - 8
粉絲 - 0
[+加關(guān)注](javascript:void(0);)
0
0
posted @ 2021-06-13 21:00 好大的風(fēng) 閱讀(16) 評論(0) 編輯 [收藏](javascript:void(0)) [舉報](javascript:void(0))
