Java tutorial
/** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.manydesigns.portofino.utils; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParser.Feature; 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; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * ??JacksonJSON String<->Java ObjectMapper. ???, ??builder. */ 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); } public static JsonMapper getInstance() { return new JsonMapper(Include.NON_DEFAULT).enableSimple(); } /** * 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,?. * * @see #createCollectionType(Class, Class...) */ @SuppressWarnings("unchecked") 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 Type: ArrayList<MyBean>, constructCollectionType(ArrayList.class,MyBean.class) * HashMap<String,MyBean>, (HashMap.class,String.class, MyBean.class) */ public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); } /** * JSON??BeanBean?. */ @SuppressWarnings("unchecked") public <T> T update(String jsonString, T object) { try { return (T) 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); } return null; } /** * JSONP?. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); } /** * ?EnumtoStringEnum, FalseEnumname()Enum, ?False. ??Mapper, ?. */ public JsonMapper enableEnumUseToString() { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); return this; } /** * ?JaxbAnnotationPOJOannotation?Jackson? jaxbannotation??jackson */ public JsonMapper enableJaxbAnnotation() { JaxbAnnotationModule module = new JaxbAnnotationModule(); mapper.registerModule(module); return this; } /** * ??? ????? */ public JsonMapper enableSimple() { mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); return this; } /** * ?Mapper??API. */ public ObjectMapper getMapper() { return mapper; } /** * */ public static void main(String[] args) { // List<String> months = Lists.newArrayList(); for (int t_i = 1; t_i <= 12; t_i++) { months.add(t_i + ""); } String json = JsonMapper.getInstance().toJson(months); System.out.println(json); List<Map<String, Object>> list = Lists.newArrayList(); Map<String, Object> map = Maps.newHashMap(); map.put("id", 1); map.put("pId", -1); map.put("name", ""); list.add(map); map = Maps.newHashMap(); map.put("id", 2); map.put("pId", 1); map.put("name", ""); map.put("open", true); list.add(map); json = JsonMapper.getInstance().toJson(list); System.out.println(json); } }