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. Swift数组的加法运算符用法:array1 += array2

    var stringList1 = [String]() //创建String类型空数组 var stringList2 = ["1", "3", " ...

  2. Zabbix探索:资产信息的妙用

    前一阵子还在考虑CMDB的问题,因此Zabbix中的Inventory,也就是所谓的资产信息,遭到了我的不少鄙视. 这几天在研究告警通知对应责任人的问题,突然想起Zabbix的资产信息中应该有这么一栏 ...

  3. 高质量、处于持续更新的R包

    本文在Creative Commons许可证下发布 自由软件的问题是开发人员没有稳定的资金来源支持,可能更新上做不到持续.经过考证和圈内朋友的帮助,现在把R包中高质量.持续更新的跟大数据事业相关的R包 ...

  4. 【Spark学习】Apache Spark安全机制

    Spark版本:1.1.1 本文系从官方文档翻译而来,转载请尊重译者的工作,注明以下链接: http://www.cnblogs.com/zhangningbo/p/4135808.html 目录 W ...

  5. POJ2778&HDU2243&POJ1625(AC自动机+矩阵/DP)

    POJ2778 题意:只有四种字符的字符串(A, C, T and G),有M中字符串不能出现,为长度为n的字符串可以有多少种. 题解:在字符串上有L中状态,所以就有L*A(字符个数)中状态转移.这里 ...

  6. JS 计算日期天数差

    function dayDiffer(startDate,endDate){ console.info((endDate.getTime - startDate.getTime())/(24*60*6 ...

  7. Android实例-TRectangle加载图片(XE8+小米2)

    结果: 1.加载图片很流畅,可以做背景用. 2.现在是加载了正形与圆形,其他形状能不能加载呢?自己测试哦,要多动手才行. 3.需要把图片打到包里哦(路径为“assets\internal\”). 实例 ...

  8. hdoj 2120 Ice_cream's world I【求成环数】

    Ice_cream's world I Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Othe ...

  9. CALayer精讲

    前言 CALayer包含在QuartzCore框架中,这是一个跨平台的框架,既可以用在iOS中又可以用在Mac OS X中.后面要学Core Animation就应该先学好Layer(层). 我们看一 ...

  10. Google maps library的使用

    公司的项目中用到了google地图API, 使用Google API开发就会用到Marker, 用来在google 地图上标注位置 但是google marker使用过程中也有个问题,就是如果在goo ...