使用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端



服务器端:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值