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. linux time命令参数--执行命令并计时

    [命令]time — 执行命令并计时 [格式]time [-p] command [arguments...] [说明] 执行命令行"command [arguments...]" ...

  2. 模拟post请求方法

    2

  3. 扩展类加载器-------改变JAVA的父优先类加载顺序

    java的类加载机制默认情况下是采用委托模型:当加载某个类时JVM会首先尝试用当前类加载器的父类加载器加载该类,若父类加载器加载不到再由当前类加载器来加载,因此这种模型又叫做“父优先”模型. 但是在实 ...

  4. 《深入Java虚拟机学习笔记》- 第7章 类型的生命周期/对象在JVM中的生命周期

    一.类型生命周期的开始 如图所示 初始化时机 所有Java虚拟机实现必须在每个类或接口首次主动使用时初始化: 以下几种情形符合主动使用的要求: 当创建某个类的新实例时(或者通过在字节码中执行new指令 ...

  5. Android Activity四种加载方式

    Android之四种加载方式 (http://marshal.easymorse.com/archives/2950 图片) 在多Activity开发中,有可能是自己应用之间的Activity跳转,或 ...

  6. UVA 11488-Hyper Prefix Sets(Trie)

    题意: 给一个01串的集合,一个集合的幸运值是串的个数*集合中串的最大公共前缀 ,求所有子集中最大幸运值 分析: val[N]表示经过每个节点串的个数求幸运值 求就是每个节点值*该节点的深度 搜一遍树 ...

  7. HDU 5534 Partial Tree 完全背包

    一棵树一共有2*(n-1)度,现在的任务就是将这些度分配到n个节点,使这n个节点的权值和最大. 思路:因为这是一棵树,所以每个节点的度数都是大于1的,所以事先给每个节点分配一度,答案 ans=f[1] ...

  8. 17个Web前端开发工程师必看的国外网站

    Web设计是一个不断变化的领域,因此掌握最新的发展趋势及技术动向对设计师来说非常重要,无论是学习新技术,还是寻找免费资源与工具,设计博客都是很不错的去处. 1. Smashing Magazine S ...

  9. leetcode@ [289] Game of Life (Array)

    https://leetcode.com/problems/game-of-life/ According to the Wikipedia's article: "The Game of ...

  10. linux内存负载分析

    衡量内存负载的一个很重要的指标就是页面置换的频率.当linux系统频繁的对页进行换进换出 的时候,说明物理内存不过,不得不进行频繁的置换页面. 使用vmstat(virtual memory stat ...