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

2024-08-20 20:38

本文主要是介绍Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

JSON介绍:

JSON:JavaScript对象表示法
JSON是存储和交换文本信息的语法。
特点:

  1. JSON是轻量级的文本数据交换格式
  2. JSON独立于语言和平台
  3. JSON具有自我描述性,更易理解
    JSON与XML比较:
    类似XML,比XML更小、更快、更易解析
  4. 没有结束标签
  5. 更短
  6. 读写速度更快
  7. 使用数组
  8. 不使用保留字

JSON语法:

  1. 数据在名称/值对中
  2. 数据有逗号分隔
  3. 花括号保存对象
  4. 方括号保存数组

    JSON值可以是:

  5. 数字(整数或浮点数)
  6. 字符串(在双引号中)
  7. 逻辑值(true或false)
  8. 数组(在方括号中)
  9. 对象(在花括号中)
  10. null

JSON对象在花括号中书写,对象可以包含多个键值对:
eg:

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

JSON数组在方括号中书写,数组包含多个对象:
eg:

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

JSON第三方解析库介绍

Gson的简介和特点:
Gson是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库。可以将一个JSON字符串转成一个Java对象,或者反过来。
Gson的特点:

  1. 快速、高效
  2. 代码量小、简洁
  3. 面向对象(Gson处理和解析JSON是采用面向对象的方式)
  4. 数据传递和解析方便

Fast-json简介和特点:
Fastjson是一个性能很好的Java语言实现的JSON解析器和生成器,来自阿里巴巴的工程师开发。具有极快的性能,超越任何其他的Java json parser。

Fast-json特点:

  1. 快速FAST(比其他任何基于Java的解析器和生成器更快,包括jackson)
  2. 强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
  3. 零依赖(没有依赖其他任何类库,除了JDK)
  4. 支持注解、支持全类型序列化

解析JSON数据

1.使用Java自带的方法解析和生成json数据的方法:

要解析的文件内容:

{"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数据
//      dealJSON();//生成JSON数据createJSON();}/*** 生成JSON数据*/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数据*/private void dealJSON() {System.out.println("---------");try {InputStreamReader inputStreamReader = new InputStreamReader(getAssets().open("test.json"), "UTF-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);// 将文本中的所有数据都读取到一个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();}}
}

解析结果:
这里写图片描述
生成的json数据tostring()后的结果:
这里写图片描述

Gson基本用法:

  1. 定义实体类(注意:定义的实体类中属性名要与json返回的键名一致)
  2. 根据需要可以将JSON生成单个实体或列表实体集合

使用Gson解析JsonObject、JsonArray、将实体类转为JSON数据的例子:

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数据private void dealData(String result) {Gson gson = new Gson();//fromJson()方法中分别是:要解析的数据,要解析成的类型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数据:

{"resultcode": "200","reason": "Return Successd!","result": {"area": "北京市","location": "百度公司电信节点"},"error_code": 0
}

运行结果:
这里写图片描述

Fast-json的基本用法:

  1. 定义实体类(注意:实体类中的属性名称要与JSON数据中的键名一致)
  2. 根据需要可以将JSON生成单个实体或列表实体集合

    使用Fast-json解析JsonObject、JsonArray、将实体类转为JSON数据的例子:

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库解析JSON数据private void dealData(String result) {//parseObject()方法中参数说明:result 需要解析的JSON字符串、Book.class 要解析成的类型Book book = JSON.parseObject(result, Book.class);Log.i("tag", "书名:"+book.getTitle()+"内容摘要:"+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数据:

{"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": "日本文学","title": "日本文学"},{"count": 38,"name": "小说","title": "小说"},{"count": 32,"name": "满月之夜白鲸现","title": "满月之夜白鲸现"},{"count": 15,"name": "爱情","title": "爱情"},{"count": 8,"name": "純愛","title": "純愛"},{"count": 8,"name": "外国文学","title": "外国文学"}],"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": "满月之夜白鲸现","url": "http://api.douban.com/v2/book/1220562","alt_title": "","author_intro": "","summary": "那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。","price": "15.00元"
}

运行结果截图:
这里写图片描述

如果想要将Book实体类或者Book实体类集合转换成JSON数据:
只需要在dealData()方法中添加如下代码:

//使用Fast-json库解析JSON数据private void dealData(String result) {//parseObject()方法中参数说明:result 需要解析的JSON字符串、Book.class 要解析成的类型Book book = JSON.parseObject(result, Book.class);Book book1 = new Book();book1.setTitle("book1");//将实体类对象转换成JSON数据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);//将实体类集合转换为JSON数据JSON.toJSON(list);Log.i("tag", "书名:"+book.getTitle()+"内容摘要:"+book.getSummary()+"tags的size:"+book.getTags().size());}

使用Gson或Fast-json库解析复杂的JSON数据:
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库解析JSON数据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库解析JSON数据
//          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数据:

{"error_code": 0,"reason": "Success","result": {"data": [{"title": "美国70年:大而不倒的阴谋政治","code": 39705},{"title": "关情","code": 39706},{"title": "维基大战前传1:阿桑奇和他的黑客战友","code": 39707},{"title": "大逆转:大败局之后的复活密码","code": 39708},{"title": "我是夜场女企划(全本)","code": 39709},{"title": "杜月笙传(上、中、下)","code": 39710},{"title": "你走以后","code": 39711},{"title": "创造贝因美——服务经济时代的公司革命","code": 39712},{"title": "9999滴眼泪","code": 39716},{"title": "新闻人","code": 39717},{"title": "草莽生长:十大首富的创富之道","code": 39718},{"title": "1块变10块的投资分配法","code": 39719},{"title": "阿嬷,我回来了","code": 39720},{"title": "换个方式好好爱","code": 39721},{"title": "权力野兽朱元璋3(大结局)","code": 39722},{"title": "流动中国","code": 39723},{"title": "问你爸去","code": 39724},{"title": "667公里的吻","code": 39725},{"title": "给你一个公司,看你怎么管","code": 39726},{"title": "职场中50个第一次","code": 39727},{"title": "从零开始学K线","code": 39728},{"title": "非常印度","code": 39729},{"title": "远征流在缅北的血","code": 39731},{"title": "这样喝咖啡最健康","code": 39732},{"title": "扑克脸:Lady Gaga传","code": 39733},{"title": "换个姿势爱","code": 39734},{"title": "30年后,你拿什么养活自己2","code": 39735},{"title": "暗权力——黑道启示录","code": 39736},{"title": "重金求子","code": 39738},{"title": "成为作家","code": 39739},{"title": "寻路中国:从乡村到工厂的自驾之旅","code": 39740},{"title": "一个人的旅行","code": 39741},{"title": "女人29岁","code": 39742},{"title": "有爱无爱一身轻","code": 39743},{"title": "嫁人的资本","code": 39744},{"title": "小女人隐私报告2","code": 39745},{"title": "小女人隐私报告1","code": 39746},{"title": "冷血感情信箱","code": 39747},{"title": "为什么男人爱说谎女人爱哭","code": 39748},{"title": "像女人一样行动,像男人一样思考","code": 39749},{"title": "男人来自火星·白金升级版","code": 39750},{"title": "放下","code": 39751},{"title": "爱的锁钥","code": 39752},{"title": "爱情纪","code": 39753},{"title": "婚恋中女人不能犯的100个错误","code": 39754},{"title": "婚恋中男人不能犯的100个错误","code": 39755},{"title": "再婚书","code": 39756},{"title": "幸福太太完全自助宝典","code": 39757},{"title": "婚恋急诊室","code": 39758},{"title": "男人是野生动物 女人是筑巢动物","code": 39759}]}
}

运行结果截图:
这里写图片描述

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

这篇关于Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1091115

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没