本文主要是介绍Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
JSON介绍:
JSON:JavaScript对象表示法
JSON是存储和交换文本信息的语法。
特点:
- JSON是轻量级的文本数据交换格式
- JSON独立于语言和平台
- JSON具有自我描述性,更易理解
JSON与XML比较:
类似XML,比XML更小、更快、更易解析 - 没有结束标签
- 更短
- 读写速度更快
- 使用数组
- 不使用保留字
JSON语法:
- 数据在名称/值对中
- 数据有逗号分隔
- 花括号保存对象
-
方括号保存数组
JSON值可以是:
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true或false)
- 数组(在方括号中)
- 对象(在花括号中)
- 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的特点:
- 快速、高效
- 代码量小、简洁
- 面向对象(Gson处理和解析JSON是采用面向对象的方式)
- 数据传递和解析方便
Fast-json简介和特点:
Fastjson是一个性能很好的Java语言实现的JSON解析器和生成器,来自阿里巴巴的工程师开发。具有极快的性能,超越任何其他的Java json parser。
Fast-json特点:
- 快速FAST(比其他任何基于Java的解析器和生成器更快,包括jackson)
- 强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
- 零依赖(没有依赖其他任何类库,除了JDK)
- 支持注解、支持全类型序列化
解析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基本用法:
- 定义实体类(注意:定义的实体类中属性名要与json返回的键名一致)
- 根据需要可以将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的基本用法:
- 定义实体类(注意:实体类中的属性名称要与JSON数据中的键名一致)
-
根据需要可以将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}]}
}
运行结果截图:
版权声明:本文为博主原创文章,未经博主允许不得转载。
这篇关于Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!