package cn.kjxy.GSON;

 import java.util.List;

 import cn.kjxy.JSON.HttpHelpers;

 import com.google.gson.Gson;

 /**
* gson解析json对象 :
* 注意:1.建立的属性或者对象名必须与json数据中的一致才能解析出来
* 2。需导入gson-2.2.1.jar包
* 工具类需导入:commons-logging-1.1.1.jar
* httpclient-4.1.2.jar
* httpcore-4.1.2.jar
*
* @author Administrator
*
*/
class Food {
private int ret;
private List<Data> data; @Override
public String toString() {
return "Food [ret=" + ret + ", data=" + data + "]";
} } class Data { private int id;// ": "8289",
private String title;// ": "油焖大虾",
private String pic;// ": "http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg",
private int collect_num;// ": "1544",
private String food_str;// ": "大虾 葱 生姜 植物油 料酒",
private int num;// ": 1544 @Override
public String toString() {
return "Data [id=" + id + ", title=" + title + ", pic=" + pic
+ ", collect_num=" + collect_num + ", food_str=" + food_str
+ ", num=" + num + "]";
} } public class Demo2 {
public static void main(String[] args) {
// gson解析json对象
String json1 = HttpHelpers
.getResourceByInternet("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&page=1&limit=20");
parserJsonByGson(json1);
} private static void parserJsonByGson(String json1) {
// TODO Auto-generated method stub
Gson gson = new Gson();
Food food = gson.fromJson(json1, Food.class);
System.out.println(food);
} }

工具类:

 package cn.kjxy.JSON;

 import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* 请求网络的工具类
*
* @author Administrator
*
*/
public class HttpHelpers { /**
* 下载图片 保存到byte类型的数组中
*
* @param path
* 地址
* @return byte[]
*/
public static byte[] downLoadImg(String path) {
BufferedInputStream bis = null;
try {
// 1,创建HttpClient对象 Android6.0之前可以使用
HttpClient httpClient = new DefaultHttpClient();
// 2,创建请求对象+指定地址
HttpGet httpGet = new HttpGet(path);
// 3,执行请求 获得HttpResponse对象
HttpResponse response = httpClient.execute(httpGet);
// 4,获得响应码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
// 5,得到响应的HttpEntity对象
HttpEntity responseEntity = response.getEntity();
// 方法一
// bis = new BufferedInputStream(responseEntity.getContent());
// byte b[] = toByteArray(bis);
// return b; // 方法二
return EntityUtils.toByteArray(responseEntity); } } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} return null; } /**
* 把图片下载到本地磁盘
*
* @param path
*/
public static void downLoadImgToLocal(String path) {
BufferedInputStream bis = null;
BufferedOutputStream boStream = null;
try {
// 1,创建HttpClient对象 Android6.0之前可以使用
HttpClient httpClient = new DefaultHttpClient();
// 2,创建请求对象+指定地址
HttpGet httpGet = new HttpGet(path);
// 3,执行请求 获得HttpResponse对象
HttpResponse response = httpClient.execute(httpGet);
// 4,获得响应码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
// 5,得到响应的HttpEntity对象
HttpEntity responseEntity = response.getEntity();
// 方法一
// bis = new BufferedInputStream(responseEntity.getContent());
// byte b[] = toByteArray(bis); // 方法二
byte b[] = EntityUtils.toByteArray(responseEntity);
String endsWith = path.substring(path.lastIndexOf("."));
boStream = new BufferedOutputStream(new FileOutputStream(
(int) (Math.random() * 100) + endsWith));
boStream.write(b); } } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (boStream != null) {
try {
boStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} } /**
* 从互联网获取文本 json xml
*
* @param path
* 地址
* @return 获取到的文本数据
*/ public static String getResourceByInternet(String path) {
BufferedReader bReader = null;
try {
// 1,创建HttpClient对象 Android6.0之前可以使用
HttpClient httpClient = new DefaultHttpClient();
// 2,创建请求对象+指定地址
HttpGet httpGet = new HttpGet(path);
// 3,执行请求 获得HttpResponse对象
HttpResponse response = httpClient.execute(httpGet);
// 4,获得响应码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
// 得到HttpEntity对象
HttpEntity responseEntity = response.getEntity();
// 方法一
// bReader = new BufferedReader(new
// InputStreamReader(responseEntity.getContent()));
// StringBuilder sbBuilder = new StringBuilder();
// String line = null;
// while ((line = bReader.readLine()) != null) {
// sbBuilder.append(line);
// }
//
// return sbBuilder.toString(); // 方法二
return EntityUtils.toString(responseEntity); } } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bReader != null) {
try {
bReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} return null; } public static byte[] toByteArray(BufferedInputStream bufferedInputStream) {
byte b[] = new byte[1024 * 1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while ((len = bufferedInputStream.read(b)) != -1) {
baos.write(b, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return baos.toByteArray(); } public static String upLoadData(String path, Map<String, String> map) {
BufferedReader bReader = null;
try {
// 1,创建HttpClient对象 Android6.0之前可以使用
HttpClient httpClient = new DefaultHttpClient();
// 2,创建请求对象+指定地址
HttpPost httpPost = new HttpPost(path);
// 设置用于发送到服务端的参数
List<NameValuePair> list = new ArrayList<NameValuePair>(); for (String string : map.keySet()) {
list.add(new BasicNameValuePair(string, map.get(string)));
}
HttpEntity requestEntity = new UrlEncodedFormEntity(list, "gbk");
httpPost.setEntity(requestEntity); // 3,执行请求 获得HttpResponse对象
HttpResponse response = httpClient.execute(httpPost);
// 4,获得响应码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
// 得到HttpEntity对象
HttpEntity responseEntity = response.getEntity();
// 方法一
// bReader = new BufferedReader(new
// InputStreamReader(responseEntity.getContent()));
// StringBuilder sbBuilder = new StringBuilder();
// String line = null;
// while ((line = bReader.readLine()) != null) {
// sbBuilder.append(line);
// }
//
// return sbBuilder.toString(); // 方法二
return EntityUtils.toString(responseEntity, "gbk"); } } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bReader != null) {
try {
bReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} return null; } public static void main(String[] args) {
byte b[] = downLoadImg("http://images.china.cn/attachement/jpg/site1000/20140313/844bf52c7d7c148b8abc05.jpg");
BufferedOutputStream bufferedOutputStream;
try {
bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream("ceo.jpg"));
// bufferedOutputStream.write(b); } catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // downLoadImgToLocal("http://images.china.cn/attachement/jpg/site1000/20140313/844bf52c7d7c148b8abc05.jpg"); // System.out.println(getResourceByInternet("http://www.doukantv.com/api/hot/?type=movie&cli=ipad&sys_ver=7.1.1&ver=2.1"));
Map<String, String> map = new HashMap<String, String>();
map.put("uname", "张三");
map.put("pwd", "admin");
System.out.println(upLoadData(
"http://172.20.136.5:8080/2016_05_27_server/login", map)); } }

JAVA_Gson_example的更多相关文章

随机推荐

  1. 【JMeter】ant+jmeter生成html报告

    源博文来自于  http://my.oschina.net/hellotest/blog/517518 主要应用于接口的回归或者性能的简单查看功能.操作为先在jmeter中写好测试计划,保存为jmx文 ...

  2. winform中设置FormBorderStyle为None后点击任务栏自动最小化实现

    在winform编程中,有时候我们可能对窗体样式需要定义,不适用系统自带的样式,这样我们可以设置FormBorderStyle属性为None.但是设置了FormBorderStyle为None后,我们 ...

  3. 如何查看.Net FrameWork,VC++ 等安装包的启动参数

    最近做了一个客户端的程序,客户端程序运行环境要求是.Net FrameWork 4.0 和VC++ 2012 ,在做安装包的时候需要先检测系统环境是否存在这些环境,不存在则安装对应环境. 使用工具来制 ...

  4. 建立第一个OpenGL工程(GLUT)

    本文参考了<计算机图形学>(Donald Hearn著)的第2.9节. OpenGL基本函数库用来描述图元.属性.几何变换.观察变换和进行许多其他的操作.OpenGL被设计成与硬件无关,因 ...

  5. 看雪 安卓 dex文件

    http://bbs.pediy.com/showthread.php?t=177114

  6. 基于寄存器的VM

    jvm是基于栈的,基于栈的原因是:实现简单,考虑的就是两个地方,局部变量和操作数栈 http://ifeve.com/javacode2bytecode/这几篇文章相当不错. http://redna ...

  7. code[vs]3301 Square words

    暴力枚举+最长公共子序列 #include <iostream> #include <cstring> using namespace std; int dp[510][510 ...

  8. Spring Data JAP 多个不是必填的查询条件处理

    简单的介绍一下使用场景,DAO层用Spring Data实现,dao 只有接口,实现类是容器启动时动态字节码生成,接口里定义方法,方法上@Query 里写JPQL查询语句. 基于以上的限制,如果对一个 ...

  9. java异步任务处理

    1.场景 最近做项目的时候遇到了一个小问题:从前台提交到服务端A,A调用服务端B处理超时,原因是前端一次请求往db插1万数据,插完之后会去清理缓存.发送消息. 服务端的有三个操作 a.插DB b.清理 ...

  10. linux集群时间同步

    说明:由于hadoop集群对时间要求很高,所以集群内主机要经常同步.本文档适合ubuntu.redhat系列. 注:很多内容是在网上摘录,然后试验后总结,如有疑问可留言探讨. 1.设置主机时间准确(任 ...