json解析库gson和fastjson使用

时间:2023-02-16 12:11:22
json解析库gson和fastjson使用

 

 

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。用于数据转换传输,通用于phpjavac++,C#,python等编程语言数据交换传输。客户端和服务器之间的数据交换一般采用jsonxml形式。易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)

基本结构:对象json object、数组json array

 

Gson的简介和特点

GSONGoogle开发的Java API,是google特供的用力啊在java对象和json数据之间的映射的java类库,用于转换Java对象和Json对象。

特点:

 快速、高效。

 代码量少、简洁。

 面向对象

 数据传输和解析方便

可以实现如下功能:

Gson解析JsonObject

Gson解析JsonArray

使用Gson将实体转换为Json数据

FastJson简介和特点

 Fastjson--是一款阿里巴巴的用来解析json数据格式的库,

FastJson据阿里说目前是最快json解析库。

强大(支持普通的JDK类包括任意JAVA Bean classCollectionMapDateemum

零依赖(除了jdk没有依赖其他任何库)

支持注解、支持全类型序列化(定义实体类时,就可以按序列化的方式进行直接传递)

 

 

 

FastJsonGson一样

代码下载:https://yunpan.cn/cS7fKewHF7ymj 访问密码 b4d6


gson-2.2.4.jarfastjson-1.2.5.jarvolley.jar拷贝到项目的project试图的app/libs目录下(这两个jar包可以在网络上下载如github)

json解析库gson和fastjson使用

右键 add to libarys

Json数据采用豆瓣的apid获取

https://api.douban.com/v2/book/12220562

介绍两个json数据的解析工具第一是chrome浏览器安装jsonview插件

第二是http://json.tongxiehui.net/ 在线json数据解析

 

json解析库gson和fastjson使用

json解析库gson和fastjson使用

AndroidManifest.xml中添加网络权限

 

<!--添加网络操作权限 -->
<uses-permissionandroid:name="android.permission.INTERNET"/>

创建个Bean对象BookTag。(Bean对象的变量名一定要与返回的json数据总的名字一样,这是google Gson要求的,否则无法解析)

Book.java

package czg.czggsonfastjson.Bean;



import
java.util.ArrayList;



/**

 * Created by Administrator on 2016/6/5.

 */

public class Book
{

   
private String publisher
;

   
private String title
;

   
private String summary
;

   
private ArrayList<Tag> tags
;



   
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
ArrayList<Tag> getTags() {

       
return tags
;

    }



   
public void
setTags(ArrayList<Tag> tags) {

       
this.tags
= tags;

    }



   
public
String getTitle() {

       
return title
;

    }



   
public void
setTitle(String title) {

       
this.title
= title;

    }

}

 

Tag.java
package czg.czggsonfastjson.Bean;



/**

 * Created by Administrator on 2016/6/5.

 */

public class Tag
{

   
private String count
;

   
private String name
;

   
private String title
;



   
public
String getCount() {

       
return count
;

    }



   
public void
setCount(String count) {

       
this.count
= count;

    }



   
public
String getName() {

       
return name
;

    }



   
public void
setName(String name) {

       
this.name
= name;

    }



   
public
String getTitle() {

       
return title
;

    }



   
public void
setTitle(String title) {

       
this.title
= title;

    }

}
 
activity_gson_fastjson.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"

   
xmlns:tools=
"http://schemas.android.com/tools"

   
android:layout_width=
"match_parent"

   
android:layout_height=
"match_parent"

   
android:orientation=
"vertical"

   
android:paddingBottom=
"@dimen/activity_vertical_margin"

   
android:paddingLeft=
"@dimen/activity_horizontal_margin"

   
android:paddingRight=
"@dimen/activity_horizontal_margin"

   
android:paddingTop=
"@dimen/activity_vertical_margin"

   
tools:context=".GsonFastJsonActivity"
>



    <
LinearLayout

       
android:orientation=
"horizontal"

       
android:layout_width=
"match_parent"

       
android:layout_height="wrap_content"
>



        <
TextView

       
android:layout_width=
"wrap_content"

       
android:layout_height=
"wrap_content"

       
android:text="Title:"
/>



        <
TextView

           
android:id=
"@+id/tv_Title"

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

           
android:text="标签内容"
/>

    </
LinearLayout
>



    <
LinearLayout

       
android:orientation=
"horizontal"

       
android:layout_width=
"match_parent"

       
android:layout_height="wrap_content"
>



        <
TextView

           
android:layout_width=
"wrap_content"

            
android:layout_height=
"wrap_content"

           
android:text="publisher:"
/>



        <
TextView

           
android:id=
"@+id/tv_Publisher"

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

           
android:text="出版社"
/>

    </
LinearLayout
>



    <
LinearLayout

       
android:orientation=
"horizontal"

       
android:layout_width=
"match_parent"

       
android:layout_height="wrap_content"
>



        <
TextView

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

           
android:text="Tag.size()"
/>



        <
TextView

           
android:id=
"@+id/tv_TagSize"

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

            
android:text="标签数量"
/>

    </
LinearLayout
>



    <
LinearLayout

       
android:orientation=
"horizontal"

       
android:layout_width=
"match_parent"

       
android:layout_height="wrap_content"
>



        <
Button

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

           
android:text="
采用Gson解析"

           
android:id="@+id/btn_Gson" />



        <
Button

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

            
android:text="
采用FastJson解析"

           
android:id="@+id/btn_FastJson" />





    </
LinearLayout
>

    <
LinearLayout

       
android:orientation=
"horizontal"

       
android:layout_width=
"match_parent"

       
android:layout_height="wrap_content"
>



        <
Button

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

           
android:text="FastJson
解析JsonArray"

           
android:id="@+id/btn_GetJsonArrayCountByFastJson" />



    </
LinearLayout
>

    <
LinearLayout

       
android:orientation=
"vertical"

       
android:layout_width=
"match_parent"

       
android:layout_height="wrap_content"
>



        <
TextView

           
android:layout_width=
"wrap_content"

           
android:layout_height=
"wrap_content"

            
android:textAppearance=
"?android:attr/textAppearanceLarge"

           
android:text="
书本的数量"

           
android:id="@+id/tv_bookCount" />



        <
EditText

           
android:layout_width=
"match_parent"

           
android:layout_height=
"wrap_content"

           
android:lines=
"3"

           
android:id="@+id/et_Json"
/>

    </
LinearLayout
>





</
LinearLayout>
 
GsonFastJsonActivity.java
 
package czg.czggsonfastjson;



import
android.support.v7.app.AppCompatActivity;

import
android.os.Bundle;

import
android.util.Log;

import
android.view.View;

import
android.widget.Button;

import
android.widget.EditText;

import
android.widget.TextView;

import
android.widget.Toast;



import
com.alibaba.fastjson.JSON;

import
com.alibaba.fastjson.TypeReference;

import
com.android.volley.Response;

import
com.android.volley.VolleyError;

import
com.android.volley.toolbox.StringRequest;

import
com.android.volley.toolbox.Volley;

import
com.google.gson.Gson;

import
com.google.gson.reflect.TypeToken;



import
org.json.JSONException;

import
org.json.JSONObject;



import
java.lang.reflect.Type;

import
java.util.ArrayList;

import
java.util.List;



import
czg.czggsonfastjson.Bean.Book;

import
czg.czggsonfastjson.Bean.Tag;



public class GsonFastJsonActivity extends
AppCompatActivity {

    String
URL="https://api.douban.com/v2/book/1220562"
;

    String
TAG=this
.getClass().getName();



   
private TextView tv_Title,tv_Publisher,tv_TagSize,tv_bookCount
;

   
private Button btn_Gson,btn_FastJson,btn_GetJsonArrayCountByFastJson
;

   
private EditText et_Json
;



   
@Override

   
protected void
onCreate(Bundle savedInstanceState) {

       
super
.onCreate(savedInstanceState);

        setContentView(R.layout.
activity_gson_fastjson
);

        initView();





    }



   
private void
initView() {

       
tv_Title= (TextView) findViewById(R.id.tv_Title
);

       
tv_Publisher= (TextView) findViewById(R.id.tv_Publisher
);

       
tv_TagSize = (TextView) findViewById(R.id.tv_TagSize
);

       
tv_bookCount = (TextView) findViewById(R.id.tv_bookCount
);

       
et_Json= (EditText) findViewById(R.id.et_Json
);



       
btn_Gson= (Button) findViewById(R.id.btn_Gson
);

       
btn_FastJson= (Button) findViewById(R.id.btn_FastJson
);

       
btn_GetJsonArrayCountByFastJson= (Button) findViewById(R.id.btn_GetJsonArrayCountByFastJson
);



       
btn_Gson.setOnClickListener(new
View.OnClickListener() {

           
@Override

           
public void
onClick(View v) {

                getDataVolleyForGson();



            }

        });



       
btn_FastJson.setOnClickListener(new
View.OnClickListener() {

           
@Override

           
public void
onClick(View v) {

                getDataVolleyForFastJson();



            }

        });



       
btn_GetJsonArrayCountByFastJson.setOnClickListener(new
View.OnClickListener() {

           
@Override

           
public void
onClick(View v) {



                String s_Tmp;

                s_Tmp=
et_Json
.getText().toString();

               
if (s_Tmp.equals(""
)){

                    Toast.makeText(getApplicationContext(),
"请先用FastJson获取数据,同时生成模拟数据",Toast.LENGTH_LONG
).show();

                   
return
;

                }







                List<Book> books=JSON.parseObject(s_Tmp,

                       
new
TypeReference<List<Book>>(){



                        });



               
tv_bookCount.setText("解析有"+books.size()+"本书"
);





            }

        });







    };







   
public void
getDataVolleyForFastJson() {

        StringRequest request =
new StringRequest(URL, new
Response.Listener<String>() {

           
@Override

           
public void
onResponse(String s) {

               
//Log.i(TAG,s);



               
dealDataUseFastJson(s);



            }

        },
new
Response.ErrorListener() {

           
@Override

           
public void
onErrorResponse(VolleyError volleyError) {



            }

        });



       
//
请求加入到队列

       
new Volley().newRequestQueue(getApplicationContext()).add(request);

    }



   
/**

     *
FastJson解析json数据

     * @param
s

    
*/

   
private void
dealDataUseFastJson(String s) {

        Book book = JSON.parseObject(s,Book.
class
);

       
tv_Title
.setText(book.getTitle());

       
tv_Publisher
.setText(book.getPublisher());

       
tv_TagSize.setText(book.getTags().size()+""
);







       
//
模拟加入3 本书

       
List<Book> book_list = new ArrayList<Book>();

        book_list.add(book);

        book.setTitle(
"第二本书"
);

        book_list.add(book);

        book.setTitle(
"3本书"
);

        book_list.add(book);



        String s_Tmp;

        s_Tmp=JSON.toJSONString(book_list);

       
et_Json
.setText(s_Tmp);

       
//
可以把打印logs_Tmp拷贝出来,放到在线json进行解析http://json.tongxiehui.net/

       
Log.i(TAG,s_Tmp);



    }







   
public void
getDataVolleyForGson() {

        StringRequest request =
new StringRequest(URL, new
Response.Listener<String>() {

           
@Override

           
public void
onResponse(String s) {

               
//Log.i(TAG,s);



               
dealDataUseGson(s);



            }

        },
new
Response.ErrorListener() {

           
@Override

           
public void
onErrorResponse(VolleyError volleyError) {



            }

        });



       
//
请求加入到队列

       
new Volley().newRequestQueue(getApplicationContext()).add(request);

    }



   
/**

     *
Gson解析json数据

     * @param
s

    
*/

   
private void
dealDataUseGson(String s) {

        Gson gson =
new
Gson();

        Book book = gson.fromJson(s,Book.
class
);



       
tv_Title
.setText(book.getTitle());

       
tv_Publisher
.setText(book.getPublisher());

       
tv_TagSize.setText(book.getTags().size()+""
);



       
//
下面用Gson解析jsonArray数据



       
Gson gson2 = new Gson();

        Type type=
new
TypeToken<ArrayList<Tag>>(){

        }.getType();



       
try
{

            JSONObject object =
new
JSONObject(s);

            ArrayList<Tag> tags=gson.fromJson(object.getString(
"tags"
),type);



           
if
(!tags.isEmpty()){

                Toast.makeText(getApplicationContext(),
"tags包含的记录数是:"+tags.size(),Toast.LENGTH_SHORT
).show();

            }

        }
catch
(JSONException e) {

            e.printStackTrace();

        }



    }





}