现在很多公司的项目都基于SOA架构,系统间的调用有许多方式,其中一种常见的是用HTTP协议、以JSON格式返回结果。
这使得JSON的使用更加普遍。而市面上处理JSON的框架五花八门,常见的有JSONObject、GSON、Jackson等。
现在我们来学习Jackson,及记录常用的一些例子
版本说明
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.4</version>
</dependency>
</dependencies>
最简单的例子
将Bean对象转换为JSON,在还原回来。(为了得到指定格式的日期格式,我指定了日期格式)
package com.nicchagil.demo.No001最简单的例子; import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; public class Call { @Test
public void writeJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:SS")); String json = objectMapper.writeValueAsString(new User(999, "Nick Huang", new Timestamp(Calendar.getInstance().getTimeInMillis())));
System.out.println(json);
} @Test
public void readJson() throws IOException {
String json = "{\"id\":999,\"name\":\"Nick Huang\",\"birthday\":\"2015-10-21 15:45:673\"}"; ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:SS")); User user = objectMapper.readValue(json, User.class);
System.out.println(user);
} }
还需要一个Bean类型
package com.nicchagil.demo.No001最简单的例子; import java.sql.Timestamp; public class User { private Integer id;
private String name;
private Timestamp birthday; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Timestamp getBirthday() {
return birthday;
} public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
} public User(Integer id, String name, Timestamp birthday) {
super();
this.id = id;
this.name = name;
this.birthday = birthday;
} public User() {
super();
} @Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [id=").append(id).append(", name=").append(name)
.append(", birthday=").append(birthday).append("]");
return builder.toString();
} }
日志如下
{"id":999,"name":"Nick Huang","birthday":"2015-10-22 17:34:318"}
User [id=999, name=Nick Huang, birthday=2015-10-21 15:45:00.673]
有泛型、集合的情况,如何指定转换的结构
package com.nicchagil.demo.No002含泛型和集合; import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; public class Call { @Test
public void writeJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> map = new HashMap<String, Object>();
map.put("Nick", new User(999, "Nick Huang", new Timestamp(Calendar.getInstance().getTimeInMillis())));
map.put("Robbin", new User(998, "Robbin", new Timestamp(Calendar.getInstance().getTimeInMillis()))); String json = objectMapper.writeValueAsString(map);
System.out.println(json);
} @Test
public void readJson() throws IOException {
String json = "{\"Robbin\":{\"id\":998,\"name\":\"Robbin\",\"birthday\":1445415635096},\"Nick\":{\"id\":999,\"name\":\"Nick Huang\",\"birthday\":1445415635096}}"; ObjectMapper objectMapper = new ObjectMapper(); Map<String, User> map = objectMapper.readValue(json, new TypeReference<Map<String, User>>() {});
System.out.println(map);
} }
日志如下
{"Robbin":{"id":998,"name":"Robbin","birthday":1445506610097},"Nick":{"id":999,"name":"Nick Huang","birthday":1445506610097}}
{Robbin=User [id=998, name=Robbin, birthday=2015-10-21 16:20:35.096], Nick=User [id=999, name=Nick Huang, birthday=2015-10-21 16:20:35.096]}
更复杂的结构呢
比如Map里面的不同key值对应的类型不同(我这个只是土方法,有好方法的童靴提示下哦)(>_<)
package com.nicchagil.demo.No003复杂结构; import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nicchagil.demo.No001最简单的例子.User; public class Call { @Test
public void writeJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> map = new HashMap<String, Object>();
map.put("code", "success");
map.put("data", new User(999, "Nick Huang", new Timestamp(Calendar.getInstance().getTimeInMillis()))); String json = objectMapper.writeValueAsString(map);
System.out.println(json);
} @Test
public void readJson() throws IOException {
String json = "{\"data\":{\"id\":999,\"name\":\"Nick Huang\",\"birthday\":1445502596155},\"code\":\"success\"}"; ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> map = objectMapper.readValue(json, Map.class);
Object data = map.get("data");
User user = objectMapper.convertValue(data, User.class);
map.put("data", user); System.out.println(map); /* 打印出类型 */
System.out.println("code's type : " + map.get("code").getClass().toString());
System.out.println("data's type : " + map.get("data").getClass().toString());
} }
日志如下
{"data":{"id":999,"name":"Nick Huang","birthday":1445506936594},"code":"success"}
{data=User [id=999, name=Nick Huang, birthday=2015-10-22 16:29:56.155], code=success}
code's type : class java.lang.String
data's type : class com.nicchagil.demo.No001最简单的例子.User
简单的工具类
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; public class JSONUtil { /* 公共的ObjectMapper */
private static ObjectMapper commonObjectMapper = new ObjectMapper(); static {
commonObjectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
} /**
* 转JSON
*/
public static String toJSON(Object obj) {
String json = null;
try {
json = commonObjectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("Bean->JSON转换失败");
}
return json;
} /**
* 转Bean
*/
public static <T> T toBean(String json, TypeReference<T> valueTypeRef) {
T t = null;
try {
t = commonObjectMapper.readValue(json, valueTypeRef);
} catch (IOException e) {
throw new RuntimeException("JSON->Bean转换失败");
}
return t;
} @Test
public void toJSONTest() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", "123");
map.put("name", "Nick Huang");
map.put("createTime", new Date());
map.put("updateTime", new Timestamp(new Date().getTime()));
map.put("sendTime", Calendar.getInstance()); System.out.println(JSONUtil.toJSON(map));
} @Test
public void toBeanTest() {
System.out.println(JSONUtil.toBean("{\"createTime\":\"2017-07-26 10:09:58\",\"name\":\"Nick Huang\",\"updateTime\":\"2017-07-26 10:09:58\",\"id\":\"123\",\"sendTime\":\"2017-07-26 10:09:58\"}",
new TypeReference<Map<String, Object>>() {}));
} }