GSON之JSON解析步骤
2016-04-26 10:17
573 查看
一、 谷歌GSON这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对象。
二、Gson解析Json步骤
A、服务器端将数据转换成json字符串
首先、服务器端项目要导入Gson的jar包到BuiltPath中。(
Gson的jar:http://code.google.com/p/google-gson/ 我们还可以下载gson的帮助文档)
然后将数据转为json字符串,核心函数是:
public
static String createJsonString(Object value)
{
Gson
gson = new Gson();
String str = gson.toJson(value);
return
str;
}
B、客户端将json字符串转换为相应的javaBean
首先客户端也要导入gson的两个jar包,json的jar就不需要导入了(因为android项目中已经集成了json的jar包所以这里无需导入)
1、客户端获取json字符串
public class HttpUtil
{
public static String getJsonContent(String urlStr)
{
try
{// 获取HttpURLConnection连接对象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 设置连接属性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 获取相应码
int respCode = httpConn.getResponseCode();
二、Gson解析Json步骤
A、服务器端将数据转换成json字符串
首先、服务器端项目要导入Gson的jar包到BuiltPath中。(
Gson的jar:http://code.google.com/p/google-gson/ 我们还可以下载gson的帮助文档)
然后将数据转为json字符串,核心函数是:
public
static String createJsonString(Object value)
{
Gson
gson = new Gson();
String str = gson.toJson(value);
return
str;
}
B、客户端将json字符串转换为相应的javaBean
首先客户端也要导入gson的两个jar包,json的jar就不需要导入了(因为android项目中已经集成了json的jar包所以这里无需导入)
1、客户端获取json字符串
public class HttpUtil
{
public static String getJsonContent(String urlStr)
{
try
{// 获取HttpURLConnection连接对象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 设置连接属性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 获取相应码
int respCode = httpConn.getResponseCode();
相关文章推荐
- d3.js——绘制力学图
- Javascript 获取url参数,hash值 ,cookie
- 环状图chart.js
- 未能加载文件或程序集“Newtonsoft.Json”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)
- Eclipse中jsp,html代码自动排版太丑怎么办?!改改就好了!
- JS闭包?
- js window.open打开新窗口 参数
- 用js下载文件
- 钉钉客户端JS-API权限签名算法.NET版
- JS调用Activity方法时,方法里的overridePendingTransition 不起作用
- JS如何获取页面可见区域高度
- JSON学习笔记
- jstat:虚拟机统计信息监视工具
- 初探 js对象与数组
- Extjs 4.0.7 中模式窗口的CURD
- [Angular 2] Managing State in RxJS with StartWith and Scan
- 我对js原型链的理解
- JS跨域调用之document.domain--相同基础域名页面之间的调用
- Javascript的replace函数以及PHP中的str_replace()函数
- javaScript基础