使用Gson解析Json数据案例

Posted datou_SleepyzzZ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Gson解析Json数据案例相关的知识,希望对你有一定的参考价值。

代码托管地址:https://github.com/SleepyzzZ/HttpGsonDemo


最近在做android远程控制sony相机的项目,主要通过http实现手机端与相机端的通信,其中通信协议用的是json数据格式。原本使用自带的API即JsonObject和JsonArray的配合使用来实现数据传输,之后改用goole的Gson来生成和解析Json数据。

话不多说,为了学会使用Gson,我们直接以案例的形式快速入门。

首先给出手机端和sony相机端的通信协议(此文档来自sony android api)

案例1:


案例2:


针对案例1所示的JsonExample创建序列化的Bean:

package com.sleepyzzz.httpjsontest.bean;

import java.util.Collection;
import java.util.List;

/**
 * User: datou_SleepyzzZ(SleepyzzZ19911002@126.com)
 * Date: 2016-05-30
 * Time: 13:32
 * FIXME
 */
public class WhiteBalance 

    public WhiteBalance(String method, List params, int id, String version) 
        this.method = method;
        this.params = params;
        this.id = id;
        this.version = version;
    

    private String method;

    private List params;

    private int id;

    private String version;

    public String getMethod() 
        return method;
    

    public void setMethod(String method) 
        this.method = method;
    

    public Collection getParams() 
        return params;
    

    public void setParams(List params) 
        this.params = params;
    

    public int getId() 
        return id;
    

    public void setId(int id) 
        this.id = id;
    

    public String getVersion() 
        return version;
    

    public void setVersion(String version) 
        this.version = version;
    

    @Override
    public String toString() 
        // TODO Auto-generated method stub
        return "method: "+method+"\\n"
                +"params: "+params.get(0)+","+params.get(1)+","+params.get(2)+"\\n"
                +"id: "+id+"\\n"
                +"version: "+version+"\\n";
    


针对案例2所示的JsonExample创建序列化的Bean:

package com.sleepyzzz.httpjsontest.bean;

import java.util.List;

/**
 * User: datou_SleepyzzZ(SleepyzzZ19911002@126.com)
 * Date: 2016-05-30
 * Time: 14:50
 * FIXME
 */
public class TrackFocus 

    private int id;

    private String method;

    private List<FocusPoint> params;

    private String version;

    public TrackFocus(int id, String method, List<FocusPoint> params, String version) 
        this.id = id;
        this.method = method;
        this.params = params;
        this.version = version;
    

    public int getId() 
        return id;
    

    public void setId(int id) 
        this.id = id;
    

    public String getMethod() 
        return method;
    

    public void setMethod(String method) 
        this.method = method;
    

    public List<FocusPoint> getParams() 
        return params;
    

    public void setParams(List<FocusPoint> params) 
        this.params = params;
    

    public String getVersion() 
        return version;
    

    public void setVersion(String version) 
        this.version = version;
    

    @Override
    public String toString() 
        return "id: "+id+"\\n"
                +"method: "+method+"\\n"
                +"params: "+params.get(0).getxPosition()+","+params.get(0).getyPosition()+"\\n"
                +"version: "+version+"\\n";
    

package com.sleepyzzz.httpjsontest.bean;

/**
 * User: datou_SleepyzzZ(SleepyzzZ19911002@126.com)
 * Date: 2016-05-30
 * Time: 14:51
 * FIXME
 */
public class FocusPoint 

    private double xPosition;

    private double yPosition;

    public FocusPoint(double xPosition, double yPosition) 
        this.xPosition = xPosition;
        this.yPosition = yPosition;
    

    public double getxPosition() 
        return xPosition;
    

    public void setxPosition(double xPosition) 
        this.xPosition = xPosition;
    

    public double getyPosition() 
        return yPosition;
    

    public void setyPosition(double yPosition) 
        this.yPosition = yPosition;
    



这里为了测试方便直接写一个servlet服务端demo用于与手机端通信:

package com.sleepyzzz.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class gsonserver
 */
@WebServlet("/gsonserver")
public class gsonserver extends HttpServlet 
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public gsonserver() 
        super();
        // TODO Auto-generated constructor stub
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
		// TODO Auto-generated method stub
		doPost(request, response);
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter writer = response.getWriter();
		Gson gson = new Gson();
		
		/*String WTstr = request.getParameter("jsonWT");
		WhiteBalance WTbean = gson.fromJson(WTstr, WhiteBalance.class);
		System.out.println(WTbean.toString());*/
		
		//解析来自客户端的Json数据
		String TFstr = request.getParameter("jsonTF");
		TrackFocus TFbean = gson.fromJson(TFstr, TrackFocus.class);
		System.out.println(TFbean.toString());
		
		List<Integer> result = new ArrayList<Integer>();
		result.add(0);
		Result responseBean = new Result(result, 1);
		String resJsonString = gson.toJson(responseBean, Result.class);
		writer.println(resJsonString);
	



这里只给出案例2的测试结果,其他不在赘述

大致流程:Android端生成Json发给服务端,服务端解析数据后返回Json格式,最后Android端解析服务器端返回的数据。

Android端代码片段:

package com.sleepyzzz.httpjsontest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sleepyzzz.httpjsontest.bean.FocusPoint;
import com.sleepyzzz.httpjsontest.bean.Result;
import com.sleepyzzz.httpjsontest.bean.TrackFocus;
import com.sleepyzzz.httpjsontest.bean.WhiteBalance;
import com.sleepyzzz.httpjsontest.okhttp.OkHttpUtils;
import com.sleepyzzz.httpjsontest.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MainActivity extends AppCompatActivity 

    private static final String URL = "http://10.10.77.129:8080/HttpGsonServer/gsonserver";

    @Bind(R.id.btn_whitebalance)
    Button mBtnWhitebalance;
    @Bind(R.id.tv_whitebalance)
    TextView mTvWhitebalance;
    @Bind(R.id.tv_response1)
    TextView mTvResponse1;
    @Bind(R.id.btn_trackfocus)
    Button mBtnTrackfocus;
    @Bind(R.id.tv_trackfocus)
    TextView mTvTrackfocus;
    @Bind(R.id.tv_response2)
    TextView mTvResponse2;

    private String jsonStr;

    private Gson mGson;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mGson = new Gson();
    

    //生成Json格式数据-案例1
    private void generateWTJson() 
        List params = new ArrayList();
        params.add("Color Temperature");
        params.add(true);
        params.add(2500);
        WhiteBalance bean = new WhiteBalance("setWhiteBalance",
                params, 1, "1.0");
        jsonStr = mGson.toJson(bean);
        mTvWhitebalance.setText("request: "+jsonStr);
    

    //生成Json格式数据-案例2
    private void generateTFJson() 
        List<FocusPoint> points = new ArrayList<FocusPoint>();
        points.add(new FocusPoint(23.4,45.6));
        TrackFocus trackFocus = new TrackFocus(1, "actTrackingFocus",
                points, "1.0");
        jsonStr = mGson.toJson(trackFocus);
        mTvTrackfocus.setText("request: "+jsonStr);
    

    @OnClick(R.id.btn_whitebalance, R.id.btn_trackfocus)
    public void onClick(View view) 
        switch (view.getId()) 

            case R.id.btn_whitebalance:
                generateWTJson();
                OkHttpUtils.post()
                        .url(URL)
                        .addParams("jsonWT", jsonStr)
                        .build()
                        .execute(new StringCallback() 
                            @Override
                            public void onError(Call call, Exception e) 

                            

                            //解析Json格式数据-案例1
                            @Override
                            public void onResponse(String response) 
                                Result result = mGson.fromJson(response, Result.class);
                                mTvResponse1.setText("response: "+result.toString());
                            
                        );
                break;
            case R.id.btn_trackfocus:
                generateTFJson();
                OkHttpUtils.post()
                        .url(URL)
                        .addParams("jsonTF", jsonStr)
                        .build()
                        .execute(new StringCallback() 
                            @Override
                            public void onError(Call call, Exception e) 

                            

                            //解析Json格式数据-案例2
                            @Override
                            public void onResponse(String response) 
                                Result result = mGson.fromJson(response, Result.class);
                                mTvResponse2.setText("response: "+result.toString());
                            
                        );
                break;
        
    


测试结果:

Android端



服务器端:


以上是关于使用Gson解析Json数据案例的主要内容,如果未能解决你的问题,请参考以下文章

Android JSON解析库Gson和Fast-json的使用对比和图书列表小案例

Gson解析json

Android第九讲笔记(xUtils框架,Gson框架)

java怎么使用gson解析json字符串

使用Gson解析复杂的json数据

android使用gson解析嵌套复杂的json数据,数据怎么显示到布局上,布局怎么写