1.可以利用Android API中的JsonReader解析Json數據
2.可以引入Gson的jar包,結合JavaBean解析Json數據
Bean.java
package com.sphere.json;public class Bean { /** * Bean中的數據必須與Json數據中的key鍵值 * 一一對應 名字不可更改、 * name 與json的name鍵值對應 * wife 與json數據中的wife對應 * 否則會出現讀取為null的現象 */ PRivate String name; private String wife; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWife() { return wife; } public void setWife(String wife) { this.wife = wife; } }View Code
Gson解析工具類
package com.sphere.json;import java.io.IOException;import java.io.StringReader;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import com.google.gson.stream.JsonReader;public class JsonUtils { /** * 使用JsonReader * @param data */ public void parseJson(String data){ try { //創建JsonReader對象 JsonReader reader = new JsonReader(new StringReader(data)); //開始解析數組 reader.beginArray(); while(reader.hasNext()){ //開始解析對象 reader.beginObject(); while(reader.hasNext()){ //得到鍵 String tagName = reader.nextName(); if(tagName.equals("name")){ System.out.print("name --->"+reader.nextString()); } else if(tagName.equals("wife")){ System.out.println(" wife --->"+reader.nextString()); } } //解析對象結束 reader.endObject(); } //解析數組結束 reader.endArray(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //解析json數組 返回list對象 public ArrayList<HashMap<String, String>> parseBeanFromJson(String jsonArray){ //Gson解析Json數組 Type type = new TypeToken<LinkedList<Bean>>(){}.getType(); Gson gson = new Gson(); LinkedList<Bean> beans = gson.fromJson(jsonArray, type); ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); for (Iterator iterator = beans.iterator(); iterator.hasNext();) { Bean bean = (Bean) iterator.next(); //System.out.print(bean.getName()); //System.out.println(bean.getWife()); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", bean.getName()); map.put("wife", bean.getWife()); /*添加到list中*/ list.add(map); } /*遍歷list*/ int index = 0; for (Iterator iterator = list.iterator(); iterator.hasNext();) { HashMap<String, String> hashMap = (HashMap<String, String>) iterator.next(); System.out.println("list中第"+(++index)+"個元素"+hashMap); } return list; }}
測試類Test.java
package com.sphere.json;import com.google.gson.Gson;public class Test { static String jsonArray = "[{/"name/":/"張無忌/",/"wife/":/"敏敏特穆爾/"},{/"name/":/"楊過/",/"wife/":/"小龍女/"}]"; static String jsonData = "{/"name/":/"張無忌/",/"wife/":/"敏敏特穆爾/"}"; public static void main(String[] args) { new JsonUtils().parseJson(jsonArray); System.out.println(); /**********解析Json數據***********/ Gson gson = new Gson(); Bean user = gson.fromJson(jsonData, Bean.class); System.out.println("我叫"+user.getName()+" 我妻子是"+user.getWife()); System.out.println(); /**********解析Json數組***********/ new JsonUtils().parseBeanFromJson(jsonArray); }}
輸出結果:
name --->張無忌 wife --->敏敏特穆爾name --->楊過 wife --->小龍女我叫張無忌 我妻子是敏敏特穆爾list中第1個元素{wife=敏敏特穆爾, name=張無忌}list中第2個元素{wife=小龍女, name=楊過}
假設我想跟蹤代碼查看某個gson中函數的具體實現,該如何添加對源碼信息的查看呢。
其實很簡單, 我們先下載gson-2.2.4-sources.jar這個jar包,將其拷貝到libs目錄下。
我們在代碼中使用ctrl + 左鍵 ,點擊某個gson的API函數,如下,我們查看JsonReader這個函數
eclipse跳轉到.class 頁面
我們點擊箭頭所指的按鈕attch source, 如下圖:
因為我們把source.jar拷貝到了工程目錄下 所以這里選擇workspace
選中源碼的jar
點擊確定,就可以在eclipse中查看追蹤gson的源碼了。
//------------------------------------------------------------------------------------
以下關于gson基本用法示例來自http://www.companysz.com/kunpengit/p/4001680.html
//-------------------------------------------------------------------------------------
(3)bean轉換json
Gson gson = new Gson();String json = gson.toJson(obj);obj是對象
(4)json轉換bean
Gson gson = new Gson();
String json = "{/"id/":/"2/",/"name/":/"Json技術/"}";Book book = gson.fromJson(json, Book.class);
(5)json轉換復雜的bean,比如List,Set將json轉換成復雜類型的bean,需要使用TypeTokenGson gson = new Gson();String json = "[{/"id/":/"1/",/"name/":/"Json技術/"},{/"id/":/"2/",/"name/":/"java技術/"}]";//將json轉換成ListList list = gson.fromJson(json,new TypeToken<LIST>() {}.getType());//將json轉換成SetSet set = gson.fromJson(json,new TypeToken<SET>() {}.getType());
(6)通過json對象直接操作json以及一些json的工具a)格式化JsonString json = "[{/"id/":/"1/",/"name/":/"Json技術/"},{/"id/":/"2/",/"name/":/"java技術/"}]";Gson gson = new GsonBuilder().setPrettyPrinting().create();JsonParser jp = new JsonParser();JsonElement je = jp.parse(json);json = gson.toJson(je);b)判斷字符串是否是json,通過捕捉的異常來判斷是否是jsonString json = "[{/"id/":/"1/",/"name/":/"Json技術/"},{/"id/":/"2/",/"name/":/"java技術/"}]";boolean jsonFlag;try {new JsonParser().parse(str).getAsJsonObject();jsonFlag = true;} catch (Exception e) {jsonFlag = false;}
c)從json串中獲取屬性String json = "{/"id/":/"1/",/"name/":/"Json技術/"}";String propertyName = 'id';String propertyValue = "";try {JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();propertyValue = jsonObj.get(propertyName).toString();} catch (Exception e) {propertyValue = null;}
d)除去json中的某個屬性String json = "{/"id/":/"1/",/"name/":/"Json技術/"}";String propertyName = 'id';JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();jsonObj.remove(propertyName);json = jsonObj.toString();
e)向json中添加屬性String json = "{/"id/":/"1/",/"name/":/"Json技術/"}";String propertyName = 'desc';Object propertyValue = "json各種技術的調研";JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));json = jsonObj.toString();
f)修改json中的屬性String json = "{/"id/":/"1/",/"name/":/"Json技術/"}";String propertyName = 'name';Object propertyValue = "json各種技術的調研";JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();jsonObj.remove(propertyName);jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));json = jsonObj.toString();
g)判斷json中是否有屬性String json = "{/"id/":/"1/",/"name/":/"Json技術/"}";String propertyName = 'name';boolean isContains = false ;JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();isContains = jsonObj.has(propertyName);
h)json中日期格式的處理GsonBuilder builder = new GsonBuilder();builder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");Gson gson = builder.create();然后使用gson對象進行json的處理,如果出現日期Date類的對象,就會按照設置的格式進行處理
i)json中對于Html的轉義Gson gson = new Gson();這種對象默認對Html進行轉義,如果不想轉義使用下面的方法GsonBuilder builder = new GsonBuilder();builder.disableHtmlEscaping();Gson gson = builder.create();
新聞熱點
疑難解答