JacksonJson知识集锦
基础知识
Jackson JSON 提供了一系列API,便于Java程序读写JSON字符串。它具有强大对数据绑定能力,可以方便的在Java对象和JSON字符串之间进行转换。
创建JSON
从Java对象创建(绑定)
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
ObjectMapper mapper = new ObjectMapper(); // 启用缩进,更易读 mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // 输出Map类型时,以键排序 mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); // 日期对象的默认输出格式 mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); /** * Java字段名/属性名到JSON字段的映射策略 */ mapper.setPropertyNamingStrategy( new PropertyNamingStrategy() { public String nameForField( MapperConfig config, AnnotatedField field, String defaultName ) { if ( field.getFullName().equals( "cc.gmem.vo.Entity#name" ) ) return "Entity-Name"; return super.nameForField( config, field, defaultName ); } public String nameForGetterMethod( MapperConfig config, AnnotatedMethod method, String defaultName ) { if ( method.getAnnotated().getDeclaringClass().equals( Entity.class ) && defaultName.equals( "no" ) ) return "Entity-No"; return super.nameForGetterMethod( config, method, defaultName ); } } ); // 忽略空属性/字段 mapper.setSerializationInclusion(Include.NON_EMPTY); // 把entity转换为JSON然后写入标准输出 mapper.writeValue(System.out, entity); |
从JsonNode树创建
示例代码:
1 2 3 4 5 6 7 8 9 10 11 |
// 此工厂用于创建JsonNode对象 JsonNodeFactory factory = new JsonNodeFactory( false ); // 此工厂用于创建JSON的生成器、解析器 JsonFactory jsonFactory = new JsonFactory(); // 写入到标准输出 JsonGenerator generator = jsonFactory.createGenerator( System.out ); ObjectMapper mapper = new ObjectMapper(); // 根节点 ObjectNode entity = factory.objectNode(); entity.put( "name", "entityname" ); mapper.writeTree( generator, entity ); |
构建JSON流
这种方式很不直观,但是节约内存:
解析JSON
解析JSON流
Jackson提供了一种底层API,允许逐符号的处理JSON…
阅读全文
11 years ago
0
Spring配置:集成Hibernate、JacksonJSON、AspectJ等框架
本文提及的该套配置文件,覆盖了JavaEE项目开发的最常见需求,包括:依赖注入、事务控制、AOP、任务调度、缓存、MVC框架等方面的内容。
容易改变的配置项独立到属性文件中:
Spring配置文件部分:
Spring MVC配置文件部分:
ehcache配置部分:
Web.xml配置(使用了Spring的JavaConfig):
Java Config类:
Maven依赖包列表:
Mave…
阅读全文
1 2 3 4 5 6 |
hibernateDialect=org.hibernate.dialect.MySQL5Dialect #启用了log4jdbc支持 jdbcDriver=net.sf.log4jdbc.DriverSpy jdbcDriverUrl=jdbc:log4jdbc:mysql://192.168.0.201:3306/initpemsdb1.1.1 jdbcUserName=root jdbcPassword=root |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd "> <!-- 定义属性,在后面的配置中可以使用#{appCfg.xxx}引用 --> <util:properties id="appCfg" location="classpath:applicationConfig.properties" /> <!-- 包扫描配置 --> <context:component-scan base-package="cc.gmem.demo"> <!-- 去除Java Config类 --> <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration" /> <!-- 去除Spring MVC类 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <!-- 匹配AspectJ Pattern的类被去除 --> <context:exclude-filter type="aspectj" expression="cc.gmem.demo.aop.web.*" /> </context:component-scan> <!-- 启用注解支持 --> <context:annotation-config /> <!-- 支持@Configurable注解 --> <context:spring-configured /> <!-- 启用注解方式的事务:基于AspectJ织入 --> <tx:annotation-driven transaction-manager="txManager" mode="aspectj" /> <!-- 启用注解方式的缓存配置:基于AspectJ织入 --> <cache:annotation-driven cache-manager="cacheManager" mode="aspectj" /> <!-- 启用注解方式的任务执行(例如@Async):基于AspectJ织入 --> <task:annotation-driven executor="taskExecutor" mode="aspectj" /> <!-- 任务调度器配置,pool-size为线程池大小,限制了同时最多被调度的任务 --> <task:scheduler pool-size="100" id="scheduler" /> <!-- 任务计划列表,支持固定频率、固定延迟、Cron表达式等 --> <task:scheduled-tasks scheduler="scheduler"> <task:scheduled fixed-rate="120000" method="run" ref="hibernateStatisticsMonitor" /> </task:scheduled-tasks> <!-- 任务执行器,用于异步执行任务 --> <task:executor id="taskExecutor" keep-alive="3600" pool-size="10-100" queue-capacity="10000" rejection-policy="CALLER_RUNS" /> <!-- 引入其它Spring配置文件 --> <import resource="report-and-etl.xml" /> <!-- Hibernate配置 --> <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="alias" value="connectionPool" /> <property name="driver" value="#{appCfg.jdbcDriver}" /> <property name="driverUrl" value="#{appCfg.jdbcDriverUrl}" /> <property name="user" value="#{appCfg.jdbcUserName}" /> <property name="password" value="#{appCfg.jdbcPassword}" /> <property name="statistics" value="10s" /> <property name="minimumConnectionCount" value="10" /> <property name="maximumConnectionCount" value="100" /> <property name="simultaneousBuildThrottle" value="10" /> <property name="maximumActiveTime" value="3600000" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" autowire="byName" /> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" lazy-init="true" /> <bean id="sessionFactory" p:dataSource-ref="dataSource" class="cc.gmem.demo.hibernate.AnnotationSessionFactoryBean" depends-on="appCfg" > <property name="packagesToScan"> <list> <value>cc.gmem.demo.**.domain</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=#{appCfg.hibernateDialect} hibernate.jdbc.batch_size=30 hibernate.show_sql=false hibernate.format_sql=true hibernate.generate_statistics=true hibernate.transaction.factory_class=org.hibernate.transaction.JDBCTransactionFactory hibernate.current_session_context_class=org.springframework.orm.hibernate3.SpringSessionContext hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory hibernate.hbm2ddl.auto=update #启用二级缓存 hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.SingletonEhCacheRegionFactory </value> </property> </bean> <!-- Spring缓存配置 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcache" /> </bean> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>classpath:ehcache.xml</value> </property> <property name="shared" value="true" /> </bean> <bean id="hibernateStatisticsMonitor" class="cc.gmem.demo.hibernate.HibernateStatisticsMonitor" /> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <!-- Velocity引擎配置 --> <bean id="velocityEngine" class="org.apache.velocity.app.VelocityEngine"> <constructor-arg type="java.util.Properties"> <value> <![CDATA[ #{T(org.apache.velocity.runtime.RuntimeConstants).RUNTIME_LOG_LOGSYSTEM_CLASS}=org.apache.velocity.runtime.log.Log4JLogChute runtime.log.logsystem.log4j.logger=velocityLogger #{T(org.apache.velocity.runtime.RuntimeConstants).INPUT_ENCODING}=UTF-8 #{T(org.apache.velocity.runtime.RuntimeConstants).OUTPUT_ENCODING}=UTF-8 #{T(org.apache.velocity.runtime.RuntimeConstants).VM_PERM_ALLOW_INLINE}=true #{T(org.apache.velocity.runtime.RuntimeConstants).RESOURCE_LOADER}=class #{T(org.apache.velocity.runtime.RuntimeConstants).PARSER_POOL_SIZE}=100 class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader ]]> </value> </constructor-arg> </bean> <!--国际化支持--> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <value>classpath:message.gmemdemo</value> </list> </property> <property name="defaultEncoding" value="UTF-8" /> <property name="cacheSeconds" value="5" /> </bean> <!--Jackson JSON --> <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" autowire="byType" /> <!-- Spring类型转换服务,特别是用于时间日期格式转换 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="net.greenmemory.spring.converter.DateTimeConvertor"> <constructor-arg> <array> <value>yyyy-MM-dd</value> <value>yyyy-MM-dd HH:mm:ss</value> <value>yyyy-MM-dd HH:mm:ss.SSS</value> </array> </constructor-arg> </bean> </set> </property> <property name="formatters"> <set> <bean class="org.springframework.format.datetime.DateFormatter"> <constructor-arg> <value>yyyy-MM-dd</value> </constructor-arg> </bean> </set> </property> <property name="formatterRegistrars"> <set> </set> </property> </bean> </beans> |
11 years ago
0