如何将Jackson JSON映射器与Java 8 LocalDateTime一起使用?
org.codehaus.jackson.map.JsonMappingException:无法从JSON String实例化类型[simple type,class java.time.LocalDateTime]的值; 没有单字符串构造函数/工厂方法(通过引用链:MyDTO ["field1"] - > SubDTO ["date"])
如何根据一个简单的模式(如"dd-MM-yyyy")让杰克逊序列化我的Joda DateTime对象?
我试过了:
@JsonSerialize(using=DateTimeSerializer.class)
private final DateTime date;
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
ObjectMapper mapper = new ObjectMapper()
.getSerializationConfig()
.setDateFormat(df);
Run Code Online (Sandbox Code Playgroud)
谢谢!
我正在使用Spring Boot(1.2.1),其方式与构建RESTful Web服务教程的方式类似:
@RestController
public class EventController {
@RequestMapping("/events/all")
EventList events() {
return proxyService.getAllEvents();
}
}
Run Code Online (Sandbox Code Playgroud)
所以上面,Spring MVC暗中使用Jackson将我的EventList对象序列化为JSON.
但我想对JSON格式进行一些简单的自定义,例如:
setSerializationInclusion(JsonInclude.Include.NON_NULL)
Run Code Online (Sandbox Code Playgroud)
问题是,自定义隐式JSON映射器的最简单方法是什么?
我在这篇博客文章中尝试了这种方法,创建了一个CustomObjectMapper等等,但是第3步"在Spring上下文中注册类"失败了:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'jacksonFix': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire method: public void com.acme.project.JacksonFix.setAnnotationMethodHandlerAdapter(org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter);
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. …Run Code Online (Sandbox Code Playgroud) 我有一个spring webservice,它返回一个json响应.我正在使用此处给出的示例来创建服务:http: //www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
返回json的格式为:{"name":null,"staffName":["kfc-kampar","smith"]}
我想从返回的响应中删除任何空对象,所以它看起来像这样:{"staffName":["kfc-kampar","smith"]}
我在这里找到了类似的问题,但我已经能够得到一个解决方案,例如
如何在使用基于spring注释的配置时配置MappingJacksonHttpMessageConverter?
配置jacksonObjectMapper不能在spring mvc 3中工作
如何配置spring mvc 3在json响应中不返回"null"对象?
通过阅读这些和其他来源,我认为实现我想要的最简洁的方法是使用Spring 3.1和可以在mvc-annotation中配置的消息转换器.我更新的spring配置文件是:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.mkyong.common.controller" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="true" />
<property name="supportedMediaTypes" value="application/json" />
<property name="objectMapper">
<bean class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)
服务类与mkyong.com网站上的服务类相同,只是我注释了商店名称变量的设置,所以它是null,即
@Controller
@RequestMapping("/kfc/brands")
public class JSONController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody Shop getShopInJSON(@PathVariable String name) …Run Code Online (Sandbox Code Playgroud) 杰克逊有一个注释,用于忽略类中的未知属性:
@JsonIgnoreProperties(ignoreUnknown = true)
Run Code Online (Sandbox Code Playgroud)
它允许您使用此批注忽略特定属性:
@JsonIgnore
Run Code Online (Sandbox Code Playgroud)
如果您想全局设置它,您可以修改对象映射器:
// jackson 1.9 and before
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or jackson 2.0
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Run Code Online (Sandbox Code Playgroud)
你如何使用spring全局设置它,以便它可以@Autowired在服务器启动而无需编写其他类?
Spring MVC 3.1与Jackson 2.0兼容吗?Spring MVC是否会在类路径上自动检测Jackson,并且使用JSON内容类型的请求委托给Jackson仍有效?
我有一个Spring Boot和Jetty的简单应用程序.我有一个简单的控制器返回一个具有Java 8的对象ZonedDateTime:
public class Device {
// ...
private ZonedDateTime lastUpdated;
public Device(String id, ZonedDateTime lastUpdated, int course, double latitude, double longitude) {
// ...
this.lastUpdated = lastUpdated;
// ...
}
public ZonedDateTime getLastUpdated() {
return lastUpdated;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的RestController我只是有:
@RequestMapping("/devices/")
public @ResponseBody List<Device> index() {
List<Device> devices = new ArrayList<>();
devices.add(new Device("321421521", ZonedDateTime.now(), 0, 39.89011333, 24.438176666));
return devices;
}
Run Code Online (Sandbox Code Playgroud)
我期望ZonedDateTime根据ISO格式进行格式化,但是我得到了类的整个JSON转储:
"lastUpdated":{"offset":{"totalSeconds":7200,"id":"+02:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"zone":{"id":"Europe/Berlin","rules":{"fixedOffset":false,"transitionRules":[{"month":"MARCH","timeDefinition":"UTC","standardOffset":{"totalSeconds":3600,"id":"+01:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"offsetBefore":{"totalSeconds":3600,"id":"+01:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"offsetAfter":{"totalSeconds":7200,"id":"+02:00", ...
Run Code Online (Sandbox Code Playgroud)
我只是有一个spring-boot-starter-web应用程序,使用spring-boot-starter-jetty和排除spring-boot-starter-tomcat.
杰克逊为什么在Spring Boot中表现得像这样?
**更新** …
由于对Spring仍然有点不熟悉,我遇到了一个问题,需要为Jackson实现我的自定义反序列化器.该过程在一个小教程中描述,但是,我坚持使用Spring.我不明白,在哪里
ObjectMapper mapper = new ObjectMapper();
Run Code Online (Sandbox Code Playgroud)
在Spring中,当json通过控制器类的方法反序列化时执行MVC.所以我不知道怎么做才能用自定义反序列化器替换默认的反序列化器.
任何建议最受欢迎.
我有一个反序列化问题:
这是我的班级:
public class Response {
private Object ResObj;
private int ResInt;
public Object getResObj() {
return ResObj;
}
public int getResInt() {
return ResInt;
}
}
Run Code Online (Sandbox Code Playgroud)
我想要反序列化的JSON是:
{"ResObj":{"ClientNum":"12345","ServerNum":"78945","IdNum":"020252"},"ResInt":0}
Run Code Online (Sandbox Code Playgroud)
我得到这个例外:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ResObj" , not marked as ignorable (0 known properties: ])
at [Source: java.io.StringReader@1f758500; line: 1, column: 20] (through reference chain: ["ResObj"])
Run Code Online (Sandbox Code Playgroud)
我不想补充:
@JsonIgnoreProperties(ignoreUnknown = true)
Run Code Online (Sandbox Code Playgroud)
因为我想得到ResObj ...
如果我添加注释,它会通过,但它会将其设置为null ..这是我不想要的.
当我序列化/反序列化任何对象时,所有字段名称都转换为小写.是否有任何配置可以让Jackson完全保留字段名称?用于序列化和反序列化?
(我知道@JsonProperty,但这似乎不对,因为我需要的只是杰克逊尊重已经存在的东西)
我的测试代码:
import java.io.Serializable;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
public class Test {
static class Example implements Serializable {
private String Test;
private String ABC;
private String XyZ;
public String getTest() { return Test; }
public void setTest(String test) { Test = test; }
public String getABC() { return ABC; }
public void setABC(String abc) { ABC = abc; }
public String getXyZ() { return XyZ; }
public void setXyZ(String …Run Code Online (Sandbox Code Playgroud) jackson ×10
java ×7
json ×6
spring ×5
spring-mvc ×3
spring-boot ×2
java-time ×1
jodatime ×1
web-services ×1
xml ×1