使用Gson解析Json数据案例
来源:互联网 发布:alfred mac app store 编辑:程序博客网 时间:2024/05/30 19:33
代码托管地址: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 stubdoPost(request, response);}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.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
- 使用Gson解析Json数据案例
- 使用GSON 解析JSON 数据
- 使用Gson解析json数据
- 使用Gson解析json数据
- 使用Gson解析json数据
- 使用Gson解析json数据
- 使用Gson解析json数据
- 使用Gson解析Json数据
- 使用GSON解析json数据
- 使用gson解析json数据
- 使用Gson解析json数据
- Android 使用Gson解析json案例详解
- Android 使用Gson解析json案例详解
- Android 使用Gson解析json案例详解
- 解析Json数据:使用Gson进行解析json数据<二>
- Android中使用Gson解析JSON数据
- Android中使用Gson解析JSON数据
- Android中使用Gson解析JSON数据
- centos安装NETCAT
- 无
- 先建立临时表再查询
- Linux 下常用 ftp 命令
- spring 切面,暂无更深理解
- 使用Gson解析Json数据案例
- 三种基本的存储引擎比较
- 警察与厨师
- 存储过程 返回值 procedure return values
- Android获取系统相册图片并裁剪(兼容4.4以上版本)
- JSON工具类总结
- 利用OpenCV的函数createTrackbar创建滑动条查看二值化的最佳阈值的源码及讲解
- SpringMVC学习系列(2) 之 经典的HelloWorld实现
- WPF开发一款软件自动升级组件