ORM FROM JSON

发布于 2015-09-16 / Java / 0条评论 / 558浏览

不知道该不该用个标题“ORM FROM JSON”
其实也JSON转Object 这里使用了两个主流的JSON框架“Gson”,“fastJSON”分别实现;不作评价…
我感觉很方便的,直接把数据库对应的字段转成对象,哪怕是连表,想查什么字段都行,也不用写复杂的配置文件也不用很多其他的第三方框架,Spring,JSON这些以后的后台项目都的必不可少的…
不多说了,直接上马吧

MainController.java

  // 主要代码及逻辑
  long startTime = System.currentTimeMillis();
  // 查询字段
  List<Map<String, Object>> map = jdbcTemplate.queryForList("select userName from account");
  log.info("data size:{}",map.size());
  long queryTime = System.currentTimeMillis();
  
  String str = map.toString();
  log.info("Query time:" + (queryTime - startTime));
  List list = new com.google.gson.Gson().fromJson(str, new TypeToken<List>() {}.getType());
  
  long convert1Time = System.currentTimeMillis();
  log.info("gson Convert time:{}",(convert1Time - queryTime));
  String json = com.alibaba.fastjson.JSON.toJSONString(map);

  List list2 = com.alibaba.fastjson.JSON.parseArray(json, User.class);
  //List list2 = com.alibaba.fastjson.JSON.parseObject(json, new TypeReference<List>() {}.getType());
  long convert2Time = System.currentTimeMillis();
  log.info("fastjson Convert time:{}",(convert2Time - convert1Time));

User.java

  package com.denghb.example.domain;

  import java.io.Serializable;

  public class User implements Serializable {
	
	private static final long serialVersionUID = 4072236195531284427L;

	private String userName;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

  }

输出信息

[23:14:18,266] [org.springframework.jdbc.core.JdbcTemplate] Executing SQL query [select userName from account]
[23:14:18,266] [com.denghb.example.App] data size:15
[23:14:18,301] [com.denghb.example.App] Query time:36
[23:14:18,316] [com.denghb.example.App] gson Convert time:13
[23:14:18,607] [com.denghb.example.App] fastjson Convert time:293
[23:14:56,625] [org.springframework.jdbc.core.JdbcTemplate] Executing SQL query [select userName from account]
[23:14:56,625] [com.denghb.example.App] data size:15
[23:14:56,625] [com.denghb.example.App] Query time:10
[23:14:56,625] [com.denghb.example.App] gson Convert time:0
[23:14:56,625] [com.denghb.example.App] fastjson Convert time:0

洗洗睡了…

评论
站长统计