1.可以利用Android API中的JsonReader解析Json數(shù)據(jù)
2.可以引入Gson的jar包,結(jié)合JavaBean解析Json數(shù)據(jù)
Bean.java
package com.sphere.json;public class Bean { /** * Bean中的數(shù)據(jù)必須與Json數(shù)據(jù)中的key鍵值 * 一一對(duì)應(yīng) 名字不可更改、 * name 與json的name鍵值對(duì)應(yīng) * wife 與json數(shù)據(jù)中的wife對(duì)應(yīng) * 否則會(huì)出現(xiàn)讀取為null的現(xiàn)象 */ 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 { //創(chuàng)建JsonReader對(duì)象 JsonReader reader = new JsonReader(new StringReader(data)); //開始解析數(shù)組 reader.beginArray(); while(reader.hasNext()){ //開始解析對(duì)象 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()); } } //解析對(duì)象結(jié)束 reader.endObject(); } //解析數(shù)組結(jié)束 reader.endArray(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //解析json數(shù)組 返回list對(duì)象 public ArrayList<HashMap<String, String>> parseBeanFromJson(String jsonArray){ //Gson解析Json數(shù)組 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)+"個(gè)元素"+hashMap); } return list; }}
測(cè)試類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數(shù)據(jù)***********/ Gson gson = new Gson(); Bean user = gson.fromJson(jsonData, Bean.class); System.out.println("我叫"+user.getName()+" 我妻子是"+user.getWife()); System.out.println(); /**********解析Json數(shù)組***********/ new JsonUtils().parseBeanFromJson(jsonArray); }}
輸出結(jié)果:
name --->張無忌 wife --->敏敏特穆爾name --->楊過 wife --->小龍女我叫張無忌 我妻子是敏敏特穆爾list中第1個(gè)元素{wife=敏敏特穆爾, name=張無忌}list中第2個(gè)元素{wife=小龍女, name=楊過}
假設(shè)我想跟蹤代碼查看某個(gè)gson中函數(shù)的具體實(shí)現(xiàn),該如何添加對(duì)源碼信息的查看呢。
其實(shí)很簡(jiǎn)單, 我們先下載gson-2.2.4-sources.jar這個(gè)jar包,將其拷貝到libs目錄下。
我們?cè)诖a中使用ctrl + 左鍵 ,點(diǎn)擊某個(gè)gson的API函數(shù),如下,我們查看JsonReader這個(gè)函數(shù)
eclipse跳轉(zhuǎn)到.class 頁面
我們點(diǎn)擊箭頭所指的按鈕attch source, 如下圖:
因?yàn)槲覀儼裺ource.jar拷貝到了工程目錄下 所以這里選擇workspace
選中源碼的jar
點(diǎn)擊確定,就可以在eclipse中查看追蹤gson的源碼了。
//------------------------------------------------------------------------------------
以下關(guān)于gson基本用法示例來自http://www.survivalescaperooms.com/kunpengit/p/4001680.html
//-------------------------------------------------------------------------------------
(3)bean轉(zhuǎn)換json
Gson gson = new Gson();String json = gson.toJson(obj);obj是對(duì)象
(4)json轉(zhuǎn)換bean
Gson gson = new Gson();
String json = "{/"id/":/"2/",/"name/":/"Json技術(shù)/"}";Book book = gson.fromJson(json, Book.class);
(5)json轉(zhuǎn)換復(fù)雜的bean,比如List,Set將json轉(zhuǎn)換成復(fù)雜類型的bean,需要使用TypeTokenGson gson = new Gson();String json = "[{/"id/":/"1/",/"name/":/"Json技術(shù)/"},{/"id/":/"2/",/"name/":/"java技術(shù)/"}]";//將json轉(zhuǎn)換成ListList list = gson.fromJson(json,new TypeToken<LIST>() {}.getType());//將json轉(zhuǎn)換成SetSet set = gson.fromJson(json,new TypeToken<SET>() {}.getType());
(6)通過json對(duì)象直接操作json以及一些json的工具a)格式化JsonString json = "[{/"id/":/"1/",/"name/":/"Json技術(shù)/"},{/"id/":/"2/",/"name/":/"java技術(shù)/"}]";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技術(shù)/"},{/"id/":/"2/",/"name/":/"java技術(shù)/"}]";boolean jsonFlag;try {new JsonParser().parse(str).getAsJsonObject();jsonFlag = true;} catch (Exception e) {jsonFlag = false;}
c)從json串中獲取屬性String json = "{/"id/":/"1/",/"name/":/"Json技術(shù)/"}";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中的某個(gè)屬性String json = "{/"id/":/"1/",/"name/":/"Json技術(shù)/"}";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技術(shù)/"}";String propertyName = 'desc';Object propertyValue = "json各種技術(shù)的調(diào)研";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技術(shù)/"}";String propertyName = 'name';Object propertyValue = "json各種技術(shù)的調(diào)研";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技術(shù)/"}";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對(duì)象進(jìn)行json的處理,如果出現(xiàn)日期Date類的對(duì)象,就會(huì)按照設(shè)置的格式進(jìn)行處理
i)json中對(duì)于Html的轉(zhuǎn)義Gson gson = new Gson();這種對(duì)象默認(rèn)對(duì)Html進(jìn)行轉(zhuǎn)義,如果不想轉(zhuǎn)義使用下面的方法GsonBuilder builder = new GsonBuilder();builder.disableHtmlEscaping();Gson gson = builder.create();
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注