JsonObject和Gson详解

前端之家收集整理的这篇文章主要介绍了JsonObject和Gson详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参考文件http://www.cnblogs.com/xwdreamer/archive/2011/12/16/2296904.html
一、JsonObject

1.JAR包简介

要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:

  1. commons-lang.jar
  2. commons-beanutils.jar
  3. commons-collections.jar
  4. commons-logging.jar
  5. ezmorph.jar
  6. json-lib-2.4-jdk15.jar
  7. json-lib-2.4-jdk15-javadoc.jar
  8. json-lib-2.4-jdk15-sources.jar

2.JSONObject对象使用

JSON-lib包是一个beans,collections,maps,java arrays 和XML和JSON互相转换的包。在本例中,我们将使用JSONObject类创建JSONObject对象,然后我们打印这些对象的值。为了使用JSONObject对象,我们要引入"net.sf.json"包。为了给对象添加元素,我们要使用put()方法

public static User getUserFromJson(String json) {
		User user = new User();
		try {
			JSONObject obj = JSONObject.fromObject(json);
			user.setUserId(obj.getInt(Tables.User.Fields.USERID));
			user.setAccount(obj.getString(Tables.User.Fields.ACCOUNT));
			user.setPassword(obj.getString(Tables.User.Fields.PASSWORD));
			user.setGender(obj.getInt(Tables.User.Fields.GENDER));
			user.setPermission(obj.getInt(Tables.User.Fields.PERMISSION));
			user.setName(obj.getString(Tables.User.Fields.NAME));
			user.setRemark(obj.getString(Tables.User.Fields.REMARK));
			user.setContact(obj.getString(Tables.User.Fields.CONTACT));

			return user;
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}

二、Gson处理Json格式数据

1.Object to json格式

public String getAllVideosByJson() throws Exception {
		List<Video> videos = service.getAllVideos();
		StringBuilder sb = new StringBuilder();
		//Gson gson = new Gson();
		Gson gson = new Gson();
		String result = gson.toJson(videos);
		
		return result;
	}

2.json格式的字符串变为Video对象

public static List<Video> getJSONAllVideos_2() throws Exception {

		String path = "http://192.168.2.107:8080/VideoWeb/VideoServlet?format=json&type=get";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		InputStream inStream = conn.getInputStream();
		byte[] data = StreamTool.readInputStream(inStream);
		String json = new String(data);
		Type typeList = new TypeToken<ArrayList<Video>>() {
		}.getType();
		Gson gson = new Gson();
		ArrayList<Video> videos = gson.fromJson(json,typeList);
		return videos;
	}
原文链接:https://www.f2er.com/json/290561.html

猜你在找的Json相关文章