淺談在Java中JSON的多種使用方式
JSONObject 轉 JSON 字符串
JSONObject json = new JSONObject();jsonObject.put('name', 'test');String str = JSONObject.toJSONString(json);
JSON字符串轉JSON
String str = '{'name':'test'}';JSONObject json = JSONObject.parseObject(str);
實體類轉JSON
Test test = new Test();test.setName('test');String testStr = JSONObject.toJSONString(test);JSONObject json = JSONObject.parseObject(testStr);
Map轉JSON
JSONObject json = JSONObject.parseObject(JSON.toJSONString(map));
JSON轉Map
Map jsonToMap = JSONObject.parseObject(jsonObject.toJSONString()); 2. 將多個JSON合并一個
JSONObject totalJSON = new JSONObject();totalJSON.putAll(json1);totalJSON.putAll(json2);
json1,json2 為JSONObject。 最終的代碼格式:
{ json1:{}, json2:{}}3.JSON拆分
不同的需求有不同的做法,以下提供兩種解決思路
定義兩個或多個JSON進行put和remove 比如明確需要哪些字段的時候可以定義一個數組用來存放key信息。存放和刪除的時候只需要遍歷數組就可以。 遍歷JSON,獲取key,value再重新put4.JSON遍歷定義一個工具類,獲取key和value
if(object instanceof JSONObject) { JSONObject jsonObject = (JSONObject) object; for (Map.Entry<String, Object> entry: jsonObject.entrySet()) { Object o = entry.getValue(); if(o instanceof String) { System.out.println('key:' + entry.getKey() + ',value:' + entry.getValue()); } else { jsonLoop(o); } }}if(object instanceof JSONArray) { JSONArray jsonArray = (JSONArray) object; for(int i = 0; i < jsonArray.size(); i ++) { jsonLoop(jsonArray.get(i)); }}
JSONArray遍歷的方式有很多種
for
for(int i = 0; i < jsonArray.size(); i++){JSONObject json = jsonArray.getJSONObject(i);}
foreach
jsonArray.forEach(o -> { if (o instanceof JSONObject) { JSONObject json = (JSONObject) o; }
Iterator
JSONObject jsonObject = new JSONObject(jsonString);Iterator iterator = jsonObject.keys();while(iterator.hasNext()){key = (String) iterator.next();value = jsonObject.getString(key);}5.JSONPath
另外向大家推薦一個非常好用的工具:JSONPath。
JSONPath是一種簡單的方法來提取給定JSON的部分內容,使用方式類似于正則表達式。 GitHub地址: https://github.com/json-path/JsonPath
簡單描述下使用方法已經自己使用的案例 pom文件依賴:
<dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.2.0</version></dependency>
JsonPath表達式總是以與XPath表達式結合使用XML文檔相同的方式引用JSON結構。
JsonPath中的“根成員對象”始終稱為$,無論是對象還是數組。
JsonPath表達式可以使用點表示法。
這里有個表格,說明JSONPath語法元素和對應XPath元素的對比。
官方案例:
詳細大家還是參照官方解說。 下面是我寫的案例:
JSONArray jsonArray = JSONPath.read('$.ePrint.common..label');
需要注意的是這里的JSONArray是JSONPath的,所以導包是:net.minidev.json.JSONPath JSON格式不會變,所以可以轉換為alibaba的JSONArray:
com.alibaba.fastjson.JSONArray jsonArr = JSON.parse(jsonArray.toString());
這里要注意一點也是我踩過的坑:如果獲取一個JSONObject下有多個同名的JSONArray,那么返回的[]也是多個。要先遍歷獲取到的數據,在取其中的一個JSON塊。
到此這篇關于淺談在Java中JSON的多種使用方式的文章就介紹到這了,更多相關Java中JSON使用方式內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
