日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > javascript >内容正文

javascript

Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)

發(fā)布時(shí)間:2024/3/7 javascript 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

JSON介紹:

JSON:JavaScript對(duì)象表示法
JSON是存儲(chǔ)和交換文本信息的語法。
特點(diǎn):

  • JSON是輕量級(jí)的文本數(shù)據(jù)交換格式
  • JSON獨(dú)立于語言和平臺(tái)
  • JSON具有自我描述性,更易理解
    JSON與XML比較:
    類似XML,比XML更小、更快、更易解析
  • 沒有結(jié)束標(biāo)簽
  • 更短
  • 讀寫速度更快
  • 使用數(shù)組
  • 不使用保留字
  • JSON語法:

  • 數(shù)據(jù)在名稱/值對(duì)中
  • 數(shù)據(jù)有逗號(hào)分隔
  • 花括號(hào)保存對(duì)象
  • 方括號(hào)保存數(shù)組

    JSON值可以是:

  • 數(shù)字(整數(shù)或浮點(diǎn)數(shù))
  • 字符串(在雙引號(hào)中)
  • 邏輯值(true或false)
  • 數(shù)組(在方括號(hào)中)
  • 對(duì)象(在花括號(hào)中)
  • null
  • JSON對(duì)象在花括號(hào)中書寫,對(duì)象可以包含多個(gè)鍵值對(duì):
    eg:

    {"name":"zhang","sex":"男"}

    JSON數(shù)組在方括號(hào)中書寫,數(shù)組包含多個(gè)對(duì)象:
    eg:

    {"students":[{"name":"zhang","sex":"男"},{"name":"hong","sex":"女"},{"name":"fang","sex":"女"},] }

    JSON第三方解析庫(kù)介紹

    Gson的簡(jiǎn)介和特點(diǎn):
    Gson是Google提供的用來在Java對(duì)象和JSON數(shù)據(jù)之間進(jìn)行映射的Java類庫(kù)??梢詫⒁粋€(gè)JSON字符串轉(zhuǎn)成一個(gè)Java對(duì)象,或者反過來。
    Gson的特點(diǎn):

  • 快速、高效
  • 代碼量小、簡(jiǎn)潔
  • 面向?qū)ο?#xff08;Gson處理和解析JSON是采用面向?qū)ο蟮姆绞?#xff09;
  • 數(shù)據(jù)傳遞和解析方便
  • Fast-json簡(jiǎn)介和特點(diǎn):
    Fastjson是一個(gè)性能很好的Java語言實(shí)現(xiàn)的JSON解析器和生成器,來自阿里巴巴的工程師開發(fā)。具有極快的性能,超越任何其他的Java json parser。

    Fast-json特點(diǎn):

  • 快速FAST(比其他任何基于Java的解析器和生成器更快,包括jackson)
  • 強(qiáng)大(支持普通JDK類包括任意Java Bean Class、Collection、Map、Date或enum)
  • 零依賴(沒有依賴其他任何類庫(kù),除了JDK)
  • 支持注解、支持全類型序列化
  • 解析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基本用法:

  • 定義實(shí)體類(注意:定義的實(shí)體類中屬性名要與json返回的鍵名一致)
  • 根據(jù)需要可以將JSON生成單個(gè)實(shí)體或列表實(shí)體集合
  • 使用Gson解析JsonObject、JsonArray、將實(shí)體類轉(zhuǎn)為JSON數(shù)據(jù)的例子:

    GsonTest類:

    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ù),要解析成的類型Info info = gson.fromJson(result, Info.class);Log.i("tag", "location:"+info.getResult().getLocation());}}

    Info類:

    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類:

    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的基本用法:

  • 定義實(shí)體類(注意:實(shí)體類中的屬性名稱要與JSON數(shù)據(jù)中的鍵名一致)
  • 根據(jù)需要可以將JSON生成單個(gè)實(shí)體或列表實(shí)體集合

    使用Fast-json解析JsonObject、JsonArray、將實(shí)體類轉(zhuǎn)為JSON數(shù)據(jù)的例子:

  • FastJsonTest類:

    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ù)說明:result 需要解析的JSON字符串、Book.class 要解析成的類型Book book = JSON.parseObject(result, Book.class);Log.i("tag", "書名:"+book.getTitle()+"內(nèi)容摘要:"+book.getSummary()+"tags的size:"+book.getTags().size());} }

    Book類:

    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類:

    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": "小說","title": "小說"},{"count": 32,"name": "滿月之夜白鯨現(xiàn)","title": "滿月之夜白鯨現(xiàn)"},{"count": 15,"name": "愛情","title": "愛情"},{"count": 8,"name": "純愛","title": "純愛"},{"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": "滿月之夜白鯨現(xiàn)","url": "http://api.douban.com/v2/book/1220562","alt_title": "","author_intro": "","summary": "那一年,是聽莫扎特、釣鱸魚和家庭破裂的一年。說到家庭破裂,母親怪自己當(dāng)初沒有找到好男人,父親則認(rèn)為當(dāng)時(shí)是被狐貍精迷住了眼,失常的是母親,但出問題的是父親……。","price": "15.00元" }

    運(yùn)行結(jié)果截圖:

    如果想要將Book實(shí)體類或者Book實(shí)體類集合轉(zhuǎn)換成JSON數(shù)據(jù):
    只需要在dealData()方法中添加如下代碼:

    //使用Fast-json庫(kù)解析JSON數(shù)據(jù)private void dealData(String result) {//parseObject()方法中參數(shù)說明:result 需要解析的JSON字符串、Book.class 要解析成的類型Book book = JSON.parseObject(result, Book.class);Book book1 = new Book();book1.setTitle("book1");//將實(shí)體類對(duì)象轉(zhuǎn)換成JSON數(shù)據(jù)JSON.toJSON(book1);Book book2 = new Book();book2.setTitle("book2");Book book3 = new Book();book3.setTitle("book3");List<Book> list = new ArrayList<Book>();list.add(book1);list.add(book2);list.add(book3);//將實(shí)體類集合轉(zhuǎn)換為JSON數(shù)據(jù)JSON.toJSON(list);Log.i("tag", "書名:"+book.getTitle()+"內(nèi)容摘要:"+book.getSummary()+"tags的size:"+book.getTags().size());}

    使用Gson或Fast-json庫(kù)解析復(fù)雜的JSON數(shù)據(jù):
    FastAndGsonTest類:

    package com.test.FastAndGson;import java.util.ArrayList; import java.util.HashMap; import java.util.Map;import org.json.JSONException; import org.json.JSONObject;import android.app.Activity; import android.os.Bundle; import android.widget.ListView;import com.alibaba.fastjson.JSON; 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;public class FastAndGsonTest extends Activity {private ListView listView;private BookListAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_second);initView();RequestPost();}private void initView() {listView = (ListView) findViewById(R.id.id_listView);}private void RequestPost() {String url = "http://japi.juhe.cn/book/recommend.from?";final String key = "bf5cae62e7854e8969e51660c0adc910";final String cat = "1";final String ranks = "1";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("key", key);map.put("cat", cat);map.put("ranks", ranks);return map;}};Volley.newRequestQueue(getApplicationContext()).add(stringRequest);}private void dealData(String arg0) {try {//使用Fast-json庫(kù)解析JSON數(shù)據(jù)JSONObject resultObject = new JSONObject(arg0);JSONObject dataObject = new JSONObject(resultObject.getString("result"));ArrayList<Book> books = (ArrayList<Book>)JSON.parseArray(dataObject.getString("data"),Book.class);//使用Gson庫(kù)解析JSON數(shù)據(jù) // Gson gson = new Gson(); // JSONObject resultObject = new JSONObject(arg0); // JSONObject dataObject = new JSONObject(resultObject.getString("result")); // Type listType = new TypeToken<ArrayList<Book>>() { // }.getType(); // ArrayList<Book> books = gson.fromJson(dataObject.getString("data"), // listType);adapter = new BookListAdapter(FastAndGsonTest.this, books);listView.setAdapter(adapter);} catch (JSONException e) {e.printStackTrace();}}}

    BookListAdapter類:

    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類:

    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": "阿嬤,我回來了","code": 39720},{"title": "換個(gè)方式好好愛","code": 39721},{"title": "權(quán)力野獸朱元璋3(大結(jié)局)","code": 39722},{"title": "流動(dòng)中國(guó)","code": 39723},{"title": "問你爸去","code": 39724},{"title": "667公里的吻","code": 39725},{"title": "給你一個(gè)公司,看你怎么管","code": 39726},{"title": "職場(chǎng)中50個(gè)第一次","code": 39727},{"title": "從零開始學(xué)K線","code": 39728},{"title": "非常印度","code": 39729},{"title": "遠(yuǎn)征流在緬北的血","code": 39731},{"title": "這樣喝咖啡最健康","code": 39732},{"title": "撲克臉:Lady Gaga傳","code": 39733},{"title": "換個(gè)姿勢(shì)愛","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": "有愛無愛一身輕","code": 39743},{"title": "嫁人的資本","code": 39744},{"title": "小女人隱私報(bào)告2","code": 39745},{"title": "小女人隱私報(bào)告1","code": 39746},{"title": "冷血感情信箱","code": 39747},{"title": "為什么男人愛說謊女人愛哭","code": 39748},{"title": "像女人一樣行動(dòng),像男人一樣思考","code": 39749},{"title": "男人來自火星·白金升級(jí)版","code": 39750},{"title": "放下","code": 39751},{"title": "愛的鎖鑰","code": 39752},{"title": "愛情紀(jì)","code": 39753},{"title": "婚戀中女人不能犯的100個(gè)錯(cuò)誤","code": 39754},{"title": "婚戀中男人不能犯的100個(gè)錯(cuò)誤","code": 39755},{"title": "再婚書","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ǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。