Java tutorial
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package com.sxj.spring.modules.mapper; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.util.JSONPObject; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; /** * ??JacksonJSON String<->Java ObjectMapper. * * ???, ??builder. * * @author calvin */ public class JsonMapper { private static Logger logger = LoggerFactory.getLogger(JsonMapper.class); private ObjectMapper mapper; public JsonMapper() { this(null); } public JsonMapper(Include include) { mapper = new ObjectMapper(); // ? if (include != null) { mapper.setSerializationInclusion(include); } // JSONJava mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } /** * ??Null?Empty(List.isEmpty)JsonMapper,?. */ public static JsonMapper nonEmptyMapper() { return new JsonMapper(Include.NON_EMPTY); } /** * ???JsonMapper, ?? */ public static JsonMapper nonDefaultMapper() { return new JsonMapper(Include.NON_DEFAULT); } /** * Object?POJO?Collection * Null, "null". * ??, "[]". */ public String toJson(Object object) { try { return mapper.writeValueAsString(object); } catch (IOException e) { logger.warn("write to json string error:" + object, e); return null; } } /** * ???POJO?CollectionList<String>. * * JSONNull"null", Null. * JSON"[]", ?. * * ?????CollectionList<MyBean>, fromJson(String, JavaType) * * @see #fromJson(String, JavaType) */ public <T> T fromJson(String jsonString, Class<T> clazz) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return mapper.readValue(jsonString, clazz); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * ?????CollectionList<Bean>, createCollectionType()contructMapType(), ?. * * @see #createCollectionType(Class, Class...) */ public <T> T fromJson(String jsonString, JavaType javaType) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return (T) mapper.readValue(jsonString, javaType); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * Collection. */ public JavaType contructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) { return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass); } /** * Map. */ public JavaType contructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) { return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass); } /** * JSON??BeanBean?. */ public void update(String jsonString, Object object) { try { mapper.readerForUpdating(object).readValue(jsonString); } catch (JsonProcessingException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } catch (IOException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } } /** * JSONP?. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); } /** * ?EnumtoStringEnum, * FalseEnumname()Enum, ?False. * ??Mapper, ?. */ public void enableEnumUseToString() { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); } /** * ?JaxbAnnotationPOJOannotation?Jackson? * jaxbannotation??jackson */ public void enableJaxbAnnotation() { JaxbAnnotationModule module = new JaxbAnnotationModule(); mapper.registerModule(module); } /** * ?Mapper??API. */ public ObjectMapper getMapper() { return mapper; } public static void main(String... args) throws JsonProcessingException, IOException { JsonMapper mapper = JsonMapper.nonEmptyMapper(); CJ30 cj30 = new CJ30(); Map<String, String> name = cj30.getName(); name.put("2", ""); name.put("3", "?"); name.put("4", ""); name.put("5", ""); name.put("7", ""); name.put("8", "?"); Map<String, Map<String, Data>> data = cj30.getData(); Map<String, Data> subject1 = new HashMap<String, Data>(); Data d1 = new Data(); d1.setDate("01/14"); d1.setMin(41700); d1.setMax(41780); d1.setAverage(41740); subject1.put("1421164800", d1); Data d2 = new Data(); d2.setDate("01/15"); d2.setMin(41550); d2.setMax(41620); d2.setAverage(41585); subject1.put("1421251200", d2); data.put("2", subject1); Map<String, Data> subject2 = new HashMap<String, Data>(); Data d3 = new Data(); d3.setDate("01/14"); d3.setMin(12450); d3.setMax(12490); d3.setAverage(12470); subject2.put("1421164800", d3); Data d4 = new Data(); d4.setDate("01/15"); d4.setMin(12730); d4.setMax(12770); d4.setAverage(12750); subject2.put("1421251200", d4); data.put("3", subject2); String json = mapper.toJson(cj30); System.out.println(json); FileReader reader = new FileReader(new File("E:\\cj30.js")); char[] buffer = new char[1024]; int read = 0; StringBuilder sb = new StringBuilder(); while ((read = reader.read(buffer)) > 0) { sb.append(buffer, 0, read); } CJ30 fromJson = mapper.fromJson(sb.toString(), CJ30.class); System.out.println(fromJson.getName()); } } class CJ30 { private Map<String, String> name = new HashMap<String, String>(); private Map<String, Map<String, Data>> data = new HashMap<String, Map<String, Data>>(); public Map<String, String> getName() { return name; } public void setName(Map<String, String> name) { this.name = name; } public Map<String, Map<String, Data>> getData() { return data; } public void setData(Map<String, Map<String, Data>> data) { this.data = data; } } class Data { private String date; private Integer min; private Integer max; private Integer average; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Integer getMin() { return min; } public void setMin(Integer min) { this.min = min; } public Integer getMax() { return max; } public void setMax(Integer max) { this.max = max; } public Integer getAverage() { return average; } public void setAverage(Integer average) { this.average = average; } }