javascript
Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)
JSON介紹:
JSON:JavaScript對(duì)象表示法
JSON是存儲(chǔ)和交換文本信息的語(yǔ)法。
特點(diǎn):
JSON與XML比較:
類(lèi)似XML,比XML更小、更快、更易解析
JSON語(yǔ)法:
方括號(hào)保存數(shù)組
JSON值可以是:
JSON對(duì)象在花括號(hào)中書(shū)寫(xiě),對(duì)象可以包含多個(gè)鍵值對(duì):
eg:
JSON數(shù)組在方括號(hào)中書(shū)寫(xiě),數(shù)組包含多個(gè)對(duì)象:
eg:
JSON第三方解析庫(kù)介紹
Gson的簡(jiǎn)介和特點(diǎn):
Gson是Google提供的用來(lái)在Java對(duì)象和JSON數(shù)據(jù)之間進(jìn)行映射的Java類(lèi)庫(kù)。可以將一個(gè)JSON字符串轉(zhuǎn)成一個(gè)Java對(duì)象,或者反過(guò)來(lái)。
Gson的特點(diǎn):
Fast-json簡(jiǎn)介和特點(diǎn):
Fastjson是一個(gè)性能很好的Java語(yǔ)言實(shí)現(xiàn)的JSON解析器和生成器,來(lái)自阿里巴巴的工程師開(kāi)發(fā)。具有極快的性能,超越任何其他的Java json parser。
Fast-json特點(diǎn):
解析JSON數(shù)據(jù)
1.使用Java自帶的方法解析和生成json數(shù)據(jù)的方法:
要解析的文件內(nèi)容:
{"languages": [{"id": 1,"ide": "Eclipse","name": "Java"},{"id": 2,"ide": "XCode","name": "Swift"},{"id": 3,"ide": "Visual Studio","name": "C#"}],"cat": "it" } package com.example.myjsontest;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;import android.os.Bundle; import android.app.Activity; import android.view.Menu;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);System.out.println("123456789"); // //解析JSON數(shù)據(jù) // dealJSON();//生成JSON數(shù)據(jù)createJSON();}/*** 生成JSON數(shù)據(jù)*/private void createJSON() {JSONObject root = new JSONObject();try {root.put("cat", "it");// { // "id": 1, // "ide": "Eclipse", // "name": "Java" // }JSONObject lan1 = new JSONObject();lan1.put("id", 1);lan1.put("ide", "Eclipse");lan1.put("name", "Java");// { // "id": 2, // "ide": "XCode", // "name": "Swift" // }JSONObject lan2 = new JSONObject();lan2.put("id", 2);lan2.put("ide", "XCode");lan2.put("name", "Swift");// { // "id": 3, // "ide": "Visual Studio", // "name": "C#" // }JSONObject lan3 = new JSONObject();lan3.put("id", 3);lan3.put("ide", "Visual Studio");lan3.put("name", "C#");JSONArray array = new JSONArray();array.put(lan1);array.put(lan2);array.put(lan3);root.put("languages", array);System.out.println(root.toString());} catch (JSONException e) {e.printStackTrace();}}/*** 解析JSON數(shù)據(jù)*/private void dealJSON() {System.out.println("---------");try {InputStreamReader inputStreamReader = new InputStreamReader(getAssets().open("test.json"), "UTF-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);// 將文本中的所有數(shù)據(jù)都讀取到一個(gè)StringBuiler中String line;StringBuilder builder = new StringBuilder();while ((line = bufferedReader.readLine()) != null) {builder.append(line);}bufferedReader.close();inputStreamReader.close();JSONObject root = new JSONObject(builder.toString());System.out.println("cat=" + root.getString("cat"));JSONArray jsonArray = root.getJSONArray("languages");for (int i = 0; i < jsonArray.length(); i++) {JSONObject jsonObject = jsonArray.getJSONObject(i);System.out.println("=============================");System.out.println("id=" + jsonObject.getInt("id"));System.out.println("ide=" + jsonObject.getString("ide"));System.out.println("name=" + jsonObject.getString("name"));}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();}} }解析結(jié)果:
生成的json數(shù)據(jù)tostring()后的結(jié)果:
Gson基本用法:
使用Gson解析JsonObject、JsonArray、將實(shí)體類(lèi)轉(zhuǎn)為JSON數(shù)據(jù)的例子:
GsonTest類(lèi):
package com.test.Gson;import java.util.HashMap; import java.util.Map;import android.app.Activity; import android.os.Bundle; import android.util.Log;import com.android.volley.AuthFailureError; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.myjsontest.R; import com.google.gson.Gson;public class GsonTest extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);RequestPost();}private void RequestPost() {String url = "http://apis.juhe.cn/ip/ip2addr?";final String key = "6f4328d5a40d23cf9974a64976717ede";final String ip = "www.baidu.com";StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {@Overridepublic void onResponse(String arg0) {System.out.println(arg0);dealData(arg0);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {System.out.println(arg0.toString());}}){@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String,String> map = new HashMap<String,String>();map.put("ip", ip);map.put("key", key);return map;}};Volley.newRequestQueue(getApplicationContext()).add(stringRequest);}//使用Gson解析JSON數(shù)據(jù)private void dealData(String result) {Gson gson = new Gson();//fromJson()方法中分別是:要解析的數(shù)據(jù),要解析成的類(lèi)型Info info = gson.fromJson(result, Info.class);Log.i("tag", "location:"+info.getResult().getLocation());}}Info類(lèi):
package com.test.Gson;public class Info {private String resultcode;private String reason;private String error_code;private Tag result;public Tag getResult() {return result;}public void setResult(Tag result) {this.result = result;}public String getResultcode() {return resultcode;}public void setResultcode(String resultcode) {this.resultcode = resultcode;}public String getReason() {return reason;}public void setReason(String reason) {this.reason = reason;}public String getError_code() {return error_code;}public void setError_code(String error_code) {this.error_code = error_code;}}Tag類(lèi):
package com.test.Gson;public class Tag {private String area;private String location;public String getArea() {return area;}public void setArea(String area) {this.area = area;}public String getLocation() {return location;}public void setLocation(String location) {this.location = location;}}獲取到的JSON數(shù)據(jù):
{"resultcode": "200","reason": "Return Successd!","result": {"area": "北京市","location": "百度公司電信節(jié)點(diǎn)"},"error_code": 0 }運(yùn)行結(jié)果:
Fast-json的基本用法:
根據(jù)需要可以將JSON生成單個(gè)實(shí)體或列表實(shí)體集合
使用Fast-json解析JsonObject、JsonArray、將實(shí)體類(lèi)轉(zhuǎn)為JSON數(shù)據(jù)的例子:
FastJsonTest類(lèi):
package com.test.fastjson;import android.app.Activity; import android.os.Bundle; import android.util.Log;import com.alibaba.fastjson.JSON; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.myjsontest.R;public class FastJsonTest extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);RequestPost();}private void RequestPost() {String url = "https://api.douban.com/v2/book/1220562";StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {@Overridepublic void onResponse(String arg0) {System.out.println(arg0);dealData(arg0);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {System.out.println(arg0.toString());}});Volley.newRequestQueue(getApplicationContext()).add(stringRequest);}//使用Fast-json庫(kù)解析JSON數(shù)據(jù)private void dealData(String result) {//parseObject()方法中參數(shù)說(shuō)明:result 需要解析的JSON字符串、Book.class 要解析成的類(lèi)型Book book = JSON.parseObject(result, Book.class);Log.i("tag", "書(shū)名:"+book.getTitle()+"內(nèi)容摘要:"+book.getSummary()+"tags的size:"+book.getTags().size());} }Book類(lèi):
package com.test.fastjson;import java.util.ArrayList;public class Book {private String title;private String publisher;private String summary;private String price;private ArrayList<Tag> tags;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getPublisher() {return publisher;}public void setPublisher(String publisher) {this.publisher = publisher;}public String getSummary() {return summary;}public void setSummary(String summary) {this.summary = summary;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}public ArrayList<Tag> getTags() {return tags;}public void setTags(ArrayList<Tag> tags) {this.tags = tags;}}Tag類(lèi):
package com.test.fastjson;public class Tag {private String title;private String name;private String count;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCount() {return count;}public void setCount(String count) {this.count = count;}}獲取到的JSON數(shù)據(jù):
{"rating": {"max": 10,"numRaters": 343,"average": "7.0","min": 0},"subtitle": "","author": ["[日] 片山恭一"],"pubdate": "2005-1","tags": [{"count": 133,"name": "片山恭一","title": "片山恭一"},{"count": 62,"name": "日本","title": "日本"},{"count": 60,"name": "日本文學(xué)","title": "日本文學(xué)"},{"count": 38,"name": "小說(shuō)","title": "小說(shuō)"},{"count": 32,"name": "滿(mǎn)月之夜白鯨現(xiàn)","title": "滿(mǎn)月之夜白鯨現(xiàn)"},{"count": 15,"name": "愛(ài)情","title": "愛(ài)情"},{"count": 8,"name": "純愛(ài)","title": "純愛(ài)"},{"count": 8,"name": "外國(guó)文學(xué)","title": "外國(guó)文學(xué)"}],"origin_title": "","image": "http://img3.douban.com/mpic/s1747553.jpg","binding": "平裝","translator": ["豫人"],"catalog": "\n ","pages": "180","images": {"small": "http://img3.douban.com/spic/s1747553.jpg","large": "http://img3.douban.com/lpic/s1747553.jpg","medium": "http://img3.douban.com/mpic/s1747553.jpg"},"alt": "http://book.douban.com/subject/1220562/","id": "1220562","publisher": "青島出版社","isbn10": "7543632608","isbn13": "9787543632608","title": "滿(mǎn)月之夜白鯨現(xiàn)","url": "http://api.douban.com/v2/book/1220562","alt_title": "","author_intro": "","summary": "那一年,是聽(tīng)莫扎特、釣鱸魚(yú)和家庭破裂的一年。說(shuō)到家庭破裂,母親怪自己當(dāng)初沒(méi)有找到好男人,父親則認(rèn)為當(dāng)時(shí)是被狐貍精迷住了眼,失常的是母親,但出問(wèn)題的是父親……。","price": "15.00元" }運(yùn)行結(jié)果截圖:
如果想要將Book實(shí)體類(lèi)或者Book實(shí)體類(lèi)集合轉(zhuǎn)換成JSON數(shù)據(jù):
只需要在dealData()方法中添加如下代碼:
使用Gson或Fast-json庫(kù)解析復(fù)雜的JSON數(shù)據(jù):
FastAndGsonTest類(lèi):
BookListAdapter類(lèi):
package com.test.FastAndGson;import java.util.ArrayList;import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView;import com.example.myjsontest.R;public class BookListAdapter extends BaseAdapter{private Context context;private ArrayList<Book> list;public BookListAdapter(Context context,ArrayList<Book> books){this.context = context;this.list = books;}@Overridepublic int getCount() {return list.size();}@Overridepublic Object getItem(int position) {return list.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder = null;if(holder==null){convertView = View.inflate(context, R.layout.item_list, null);holder = new ViewHolder();holder.textView = (TextView) convertView.findViewById(R.id.id_textView);convertView.setTag(holder);}else{holder = (ViewHolder) convertView.getTag();}Book book = list.get(position);holder.textView.setText(book.getTitle()+"\n"+book.getCode());return convertView;}class ViewHolder{TextView textView;}}Book類(lèi):
package com.test.FastAndGson;public class Book {private String title;private String code;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}}獲取的JSON數(shù)據(jù):
{"error_code": 0,"reason": "Success","result": {"data": [{"title": "美國(guó)70年:大而不倒的陰謀政治","code": 39705},{"title": "關(guān)情","code": 39706},{"title": "維基大戰(zhàn)前傳1:阿桑奇和他的黑客戰(zhàn)友","code": 39707},{"title": "大逆轉(zhuǎn):大敗局之后的復(fù)活密碼","code": 39708},{"title": "我是夜場(chǎng)女企劃(全本)","code": 39709},{"title": "杜月笙傳(上、中、下)","code": 39710},{"title": "你走以后","code": 39711},{"title": "創(chuàng)造貝因美——服務(wù)經(jīng)濟(jì)時(shí)代的公司革命","code": 39712},{"title": "9999滴眼淚","code": 39716},{"title": "新聞人","code": 39717},{"title": "草莽生長(zhǎng):十大首富的創(chuàng)富之道","code": 39718},{"title": "1塊變10塊的投資分配法","code": 39719},{"title": "阿嬤,我回來(lái)了","code": 39720},{"title": "換個(gè)方式好好愛(ài)","code": 39721},{"title": "權(quán)力野獸朱元璋3(大結(jié)局)","code": 39722},{"title": "流動(dòng)中國(guó)","code": 39723},{"title": "問(wèn)你爸去","code": 39724},{"title": "667公里的吻","code": 39725},{"title": "給你一個(gè)公司,看你怎么管","code": 39726},{"title": "職場(chǎng)中50個(gè)第一次","code": 39727},{"title": "從零開(kāi)始學(xué)K線","code": 39728},{"title": "非常印度","code": 39729},{"title": "遠(yuǎn)征流在緬北的血","code": 39731},{"title": "這樣喝咖啡最健康","code": 39732},{"title": "撲克臉:Lady Gaga傳","code": 39733},{"title": "換個(gè)姿勢(shì)愛(ài)","code": 39734},{"title": "30年后,你拿什么養(yǎng)活自己2","code": 39735},{"title": "暗權(quán)力——黑道啟示錄","code": 39736},{"title": "重金求子","code": 39738},{"title": "成為作家","code": 39739},{"title": "尋路中國(guó):從鄉(xiāng)村到工廠的自駕之旅","code": 39740},{"title": "一個(gè)人的旅行","code": 39741},{"title": "女人29歲","code": 39742},{"title": "有愛(ài)無(wú)愛(ài)一身輕","code": 39743},{"title": "嫁人的資本","code": 39744},{"title": "小女人隱私報(bào)告2","code": 39745},{"title": "小女人隱私報(bào)告1","code": 39746},{"title": "冷血感情信箱","code": 39747},{"title": "為什么男人愛(ài)說(shuō)謊女人愛(ài)哭","code": 39748},{"title": "像女人一樣行動(dòng),像男人一樣思考","code": 39749},{"title": "男人來(lái)自火星·白金升級(jí)版","code": 39750},{"title": "放下","code": 39751},{"title": "愛(ài)的鎖鑰","code": 39752},{"title": "愛(ài)情紀(jì)","code": 39753},{"title": "婚戀中女人不能犯的100個(gè)錯(cuò)誤","code": 39754},{"title": "婚戀中男人不能犯的100個(gè)錯(cuò)誤","code": 39755},{"title": "再婚書(shū)","code": 39756},{"title": "幸福太太完全自助寶典","code": 39757},{"title": "婚戀急診室","code": 39758},{"title": "男人是野生動(dòng)物 女人是筑巢動(dòng)物","code": 39759}]} }運(yùn)行結(jié)果截圖:
總結(jié)
以上是生活随笔為你收集整理的Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 嵌入式开发中的防御性C语言编程
- 下一篇: c语言教程github,GitHub -