##Jackson转换Json##
###依赖的jar包###
jackson-annotations-2.6.0.jar
jackson-core-2.6.3.jar
jackson-databind-2.6.3.jar
注意
Jackson解析嵌套类时,内部类必须声明为static
public class Outer {
static class Inner {
public int getX() { return 5;
}
}
参见:http://cowtowncoder.com/blog/archives/2010/08/entry_411.html
###ObjectMapper和JsonGenerator###
ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//还可用注释标注在实体类上 @JsonIgnoreProperties({"property1", "property2"})
JsonGenerator
输出前需要flush(),使用后需要close
jsonGenerator = objectMapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}
POJO
AccountBean bean = new AccountBean();
bean.setAddress("china-Guangzhou");
bean.setEmail("hoojo_@126.com");
bean.setId(1);
bean.setName("hoojo");
###POJO转换成Json###
ObjectMapper
//writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
jsonGenerator.writeObject(bean);
JsonGenerator
objectMapper.writeValue(System.out, bean);
输出:{"id":1,"name":"hoojo","email":"hoojo_@126.com","address":"china-Guangzhou","birthday":null}
###Json转换成POJO###
String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
AccountBean accountBean = objectMapper.readValue(json, AccountBean.class);
###List转换成Json###
List<AccountBean> list = new ArrayList<>();
list.add(bean);
bean = new AccountBean();
bean.setId(2);
bean.setAddress("address2");
bean.setEmail("email2");
bean.setName("haha2");
list.add(bean);
ObjectMapper
//用objectMapper直接返回list转换成的JSON字符串
objectMapper.writeValueAsString(list)
//或
//objectMapper list转换成JSON字符串
objectMapper.writeValue(System.out, list);
jsonGenerator
jsonGenerator.writeObject(list);
[{"id":1,"name":"hoojo","email":"hoojo_@126.com","address":"china-Guangzhou","birthday":null},{"id":2,"name":"haha2","email":"email2","address":"address2","birthday":null}]
###Json转换成数组###
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
+"{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
AccountBean[] accountBeen = objectMapper.readValue(json, AccountBean[].class);
###Json转换成List###
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
+"{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
JavaType javaType = objectMapper.getTypeFactory().constructParametrizedType(ArrayList.class, List.class, AccountBean.class);
List<AccountBean> list = objectMapper.readValue(json, javaType);
###Json转换成List<Map>###
(所有的json对象都会直接解析成LinkedHashMap)
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"}," +
"{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
List<HashMap<String,Object>> list = objectMapper.readValue(json, List.class);
for(int i=0; i< list.size(); i++){
HashMap<String, Object> hashMap = list.get(i);
Iterator<Map.Entry<String, Object>> entryIterator = hashMap.entrySet().iterator();
while(entryIterator.hasNext()){
Map.Entry<String, Object> entry = entryIterator.next();
System.out.println(entry.getKey() +"="+ entry.getValue());
}
}
###Map转换成Json###
Map<String, Object> map = new HashMap<>();
map.put("name", bean.getName());
map.put("account", bean);
bean = new AccountBean();
bean.setAddress("china-Beijin");
bean.setEmail("hoojo@qq.com");
map.put("account2", bean);
ObjectMapper
objectMapper.writeValue(System.out, map);
JsonGenerator
jsonGenerator.writeObject(map);
{"account2":{"id":0,"name":null,"email":"hoojo@qq.com","address":"china-Beijin","birthday":null},"name":"hoojo","account":{"id":1,"name":"hoojo","email":"hoojo_@126.com","address":"china-Guangzhou","birthday":null}}
###Json转换成Map###
String json = "{\"flag\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
+"\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
第一种:解析成String-POJO
Map<String, Object> maps = new ObjectMapper().readValue(json, Map.class);
//第二个参数是Object
Iterator<Map.Entry<String,Object>> entryIterator = maps.entrySet().iterator();
while(entryIterator.hasNext()){
Map.Entry<String, Object> entry = entryIterator.next();
System.out.println(entry.getKey() + "=" + entry.getValue());
}
第二种:解析成String-LinkedHashMap<String,Map<String,Object>>
String json = "{\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
+"\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
Map<String, Map<String,Object>> maps = new ObjectMapper().readValue(json, Map.class);
Iterator<Map.Entry<String,Map<String,Object>>> entryIterator = maps.entrySet().iterator();
while(entryIterator.hasNext()){
Map.Entry<String, Map<String,Object>> entry = entryIterator.next();
System.out.println(entry.getKey()+"*");
Map<String, Object> map = entry.getValue();
Iterator<Map.Entry<String,Object>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, Object> entry1 = iterator.next();
System.out.println(entry1.getKey() + "#" + entry1.getValue());
}
}
第三种:解析成Map<String,Pojo>
String json = "{\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
+"\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
JavaType javaType = objectMapper.getTypeFactory().constructMapType(HashMap.class, String.class, AccountBean.class);
Map<String,AccountBean> map = objectMapper.readValue(json, javaType);
Iterator<Map.Entry<String, AccountBean>> entryIterator = map.entrySet().iterator();
while(entryIterator.hasNext()){
Map.Entry<String,AccountBean> entry = entryIterator.next();
System.out.println(entry.getKey() +"__");
System.out.println(entry.getValue().getAddress());
}
###复杂的json输出###
String[] arr = {"a", "b", "c"};
String str = "hell oa <>&*< world jackson!\"address\": \"address2\",\"name\":\"haha2\"";
//byte,null,boolean,number
jsonGenerator.writeBinary(str.getBytes());
jsonGenerator.writeBoolean(true);
jsonGenerator.writeNull();
jsonGenerator.writeNumber(2.2f);
//String
jsonGenerator.writeRawValue(str, 5, 5);
jsonGenerator.writeRawValue(str);
jsonGenerator.writeString(str);//前后有空格
// jsonGenerator.writeTree(JsonNodeFactory.instance.pojoNode(bean));
//前后没有空格
jsonGenerator.writeRaw('c');
jsonGenerator.writeRaw(str);
jsonGenerator.flush();
System.out.println();
//对象{"id":1,"name":"hoojo","email":"hoojo_@126.com","address":"china-Guangzhou","birthday":null}
jsonGenerator.writeObject(bean);
//对象多余{"user":{"id":1,"name":"hoojo","email":"hoojo_@126.com","address":"china-Guangzhou","birthday":null},"info":["a","b","c"]}
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField("user", bean);
jsonGenerator.writeObjectField("info", arr);
jsonGenerator.writeEndObject();
jsonGenerator.flush();
System.out.println();
//复杂对象
jsonGenerator.writeStartObject(); //{
jsonGenerator.writeObjectFieldStart("user");//user:{
jsonGenerator.writeFieldName("id");//id:1
jsonGenerator.writeNumber(1);
jsonGenerator.writeFieldName("memo");
jsonGenerator.writeString("123344556677");
jsonGenerator.writeStringField("name","jackson");//name:jackson
jsonGenerator.writeEndObject();//}
//jsonGenerator.writeStartArray(); //[
jsonGenerator.writeArrayFieldStart("info");//info:[
jsonGenerator.writeString("a");
jsonGenerator.writeNumber(22);//22
jsonGenerator.writeBoolean(true);
jsonGenerator.writeEndArray();//]
jsonGenerator.writeEndObject();//}
输出:(id前的zdef-863096486:暂时不知道怎么解决)
"aGVsbCBvYSA8PiYqJmx0IHdvcmxkIGphY2tzb24hImFkZHJlc3MiOiAiYWRkcmVzczIiLCJuYW1lIjoiaGFoYTIi" true null 2.2 oa <> hell oa <>&*< world jackson!"address": "address2","name":"haha2" "hell oa <>&*< world jackson!\"address\": \"address2\",\"name\":\"haha2\""chell oa <>&*< world jackson!"address": "address2","name":"haha2"
{"id":1,"name":"hoojo","email":"hoojo_@126.com","address":"china-Guangzhou","birthday":null} {"user":{"id":1,"name":"hoojo","email":"hoojo_@126.com","address":"china-Guangzhou","birthday":null},"info":["a","b","c"]}
{"user":{"id":1,"memo":"123344556677","name":"jackson"},"info":["a",22,true]}
###其他###