标签: jackson-databind

什么是与 Jackson 2.9.2 兼容的 Jersey 版本

你能帮我解决这两个查询/问题吗:

任何在 Jackson 2.9.2 上工作过的人都可以告诉我什么是 Jackson 2.9.2 的兼容 Jersey 版本。我目前使用的是 Jersey 2.23.2,但它不适用于 Jackson 2.9.2。我收到以下错误:

[ERROR   ] SRVE0777E: Exception thrown by application class 'org.glassfish.jersey.servlet.WebComponent.serviceImpl:489'
javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.util.BeanUtil.okNameForSetter(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMethod;)Ljava/lang/String;
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1290)
Run Code Online (Sandbox Code Playgroud)

2)总的来说,有没有办法找到罐子的组合。我在找到 Jersey 和 Spring 罐子的正确组合时也遇到过这个问题。如果有人可以指导,它会为我和其他人节省很多时间这个。

谢谢。

jersey-2.0 jackson2 jackson-databind

6
推荐指数
1
解决办法
5731
查看次数

杰克逊 java.util.Date 值在 Map<String, Object>(反)序列化

考虑这个属性

@JsonProperty
private Map<String, Object> myMap;
Run Code Online (Sandbox Code Playgroud)

当一个包含的java.util.Date值被序列化时,它不会被Date再次反序列化,因为类型信息不存在于Map<String, Object>. 我怎样才能绕过这个问题?我阅读了有关此问题的答案,将是一个解决方法,但无法区分包含日期的字符串和在地图中序列化为字符串的日期。我可以告诉 Jackson 为每个映射值包含类型信息,以便 Jackson 可以正确反序列化它们吗?

java jackson jackson-databind

6
推荐指数
1
解决办法
1391
查看次数

是否可以让 Jackson 将嵌套对象序列化为字符串

鉴于这些类:

@Value
private static class Message {
    private final String type;
    private final MyType message;
}

@Value
public class MyType {
    private final String foo;
}
Run Code Online (Sandbox Code Playgroud)

杰克逊将产生:

{
  "Type" : "Test",
  "Message" : {"foo" : "bar"}
}
Run Code Online (Sandbox Code Playgroud)

是否有某种类型的注释或指令我可以给 Jackson 以要求它将嵌套的复杂类型序列化为字符串,例如所需的 JSON 是:

{
  "Type" : "Test",
  "Message" : "{\"foo\" : \"bar\"}"
}
Run Code Online (Sandbox Code Playgroud)

我在消息字段上尝试了这两个注释:

 @JsonFormat(shape = JsonFormat.Shape.STRING)
 @JsonSerialize(as=String.class)
Run Code Online (Sandbox Code Playgroud)

两者都没有达到预期的效果。现在我的“hack”是在构建时执行此操作:

return new Message("Test", mapper.writeValueAsString(new MyType("bar")));
Run Code Online (Sandbox Code Playgroud)

我想我可以编写一个自定义序列化程序,但我想知道这是否是某种内置的标准行为。我的用例是我正在构建一个JSON负载,该负载预计包含一个字符串消息,它本身包含JSON.

环境

Jackson 版本是 2.9.0,在 Java 10 上使用 Spring Boot 2。

json jackson jackson2 jackson-databind

6
推荐指数
1
解决办法
3953
查看次数

如何为所有POJO应用程序类全局应用@JsonIgnoreProperties(value = {"id"})(jackson api)

我有多个类,对于所有这些类,我不希望id字段成为输出JSON字符串(序列化)的一部分.假设我有2节课

@JsonIgnoreProperties(value = { "id" })
public final class Person {
 private ObjectId id;
  //........
}

@JsonIgnoreProperties(value = { "id" })
public final class Address{
 private ObjectId id;
  //........
}
Run Code Online (Sandbox Code Playgroud)

现在我不想@JsonIgnoreProperties(value = { "id" })手动指定我的所有1000个类.有没有全球性的方法可以做,所以我可以将这部分应用于我的所有课程?非常类似于mapper.setSerializationInclusion(Include.NON_NULL)下面的方法?

public String serialize(T dataObject) throws IOException {
        ObjectMapper mapper = new ObjectMapper();   
        mapper.setSerializationInclusion(Include.NON_NULL);
        String result = mapper.writeValueAsString(dataObject);
        return result;
}
Run Code Online (Sandbox Code Playgroud)

我试过的一种方法是创建一个超类并在其上应用@JsonIgnoreProperties(可行).但是我还是要在每个孩子课上写"延伸",这是我不喜欢的.有没有什么方法我可以应用这个设置而不在我的pojo类中添加任何额外的东西?

java jackson jackson-databind

6
推荐指数
1
解决办法
114
查看次数

无法从 START_OBJECT 令牌中反序列化“java.lang.Boolean”实例

这是我的放置请求的控制器映射:

@PutMapping("/voteForPostByUser")
    public String vote(@RequestParam(value = "postId", required = 
true) String postId, @RequestParam(value = "userId", required = true) 
Integer userId, @RequestBody Boolean vote) {

        BlogPostVoteDTO blogPostVoteDTO = new BlogPostVoteDTO 
(postId, userId, vote);
        return 
this.blogPostService.updateBlogPostVotes(blogPostVoteDTO);  
}
Run Code Online (Sandbox Code Playgroud)

当我从 POSTMAN 运行以下请求时:

http://localhost:8082/microblog/api/voteForPostByUser?postId=5d564a2638195729900df9a6&userId=5

Request Body:
{
        "vote" : true
    }
Run Code Online (Sandbox Code Playgroud)

我得到以下异常

"status": 400,
    "error": "Bad Request",
    "message": "JSON parse error: Cannot deserialize instance of 
`java.lang.Boolean` out of START_OBJECT token; nested exception is 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
deserialize instance of `java.lang.Boolean` out of START_OBJECT token\n 
at [Source: …
Run Code Online (Sandbox Code Playgroud)

java rest json spring-boot jackson-databind

6
推荐指数
2
解决办法
2万
查看次数

当对象变量设置为 Private 时,Jackson ObjectMapper 返回 null

我得到了这个转义的 JSON

"{\"UniqueId\":[],\"CustomerOffers\":{},\"Success\":false,\"ErrorMessages\":[\"Test Message\"],\"ErrorType\":\"GeneralError\"}"
Run Code Online (Sandbox Code Playgroud)

我需要使用 Jackson 将其转换为 Java 对象。

// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'
Run Code Online (Sandbox Code Playgroud)

我创建了该类:

public class Data {

    private List<UUID> UniqueId;
    private Map<Integer, List<Integer>> CustomerOffers;
    private Boolean Success;
    private List<String> ErrorMessages;
    private String ErrorType;

    // getter, setters
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了转换它的方法

public class Deserializing {

    public void processing(String input) {

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);



        String jsonInString = "\"{\"UniqueId\":[],\"CustomerOffers\":{},\"Success\":false,\"ErrorMessages\":[\"Test Message\"],\"ErrorType\":\"GeneralError\"}\"";
        String newJSON = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(jsonInString);
        newJSON= newJSON.substring(1, jsonInString.length()-1);


            try {
            // JSON string to Java object …
Run Code Online (Sandbox Code Playgroud)

java jackson jackson-databind

6
推荐指数
2
解决办法
2万
查看次数

spring/jackson-databind 小升级后 HttpMessageConverter 不再工作

我必须升级几个包才能通过 whitesource 安全扫描,现在升级了依赖项HttpMessageConverter,以前拦截和构建响应的自定义不再有效。相关的依赖升级如下所示。

Tomcat 嵌入核心 8.5.50 -> 9.0.30

Spring Cloud 合约发布 2.0.1.RELEASE-> 2.0.6.RELEASE

Spring Boot 版本 2.0.4.RELEASE -> 2.0.6.RELEASE

杰克逊数据绑定 2.9.6 -> 2.10.0.pr1

杰克逊核心:2.10.1 -> 2.10.0.pr1

这是以前工作的自定义 HttpMessageConverter:

    private class JsonApiHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    JsonApiHttpMessageConverter() {
        super(MediaType.valueOf(ResponseType.MEDIA_TYPE_JSON_API));
    }

    @Override
    protected boolean supports(final Class<?> clazz) {
        return clazz == HttpErrorResponse.class;
    }

    @Override
    protected Object readInternal(final Class<?> clazz, final HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    protected void writeInternal(final Object o, final HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException …
Run Code Online (Sandbox Code Playgroud)

spring json spring-mvc jackson jackson-databind

6
推荐指数
0
解决办法
192
查看次数

嵌套异常是 java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ser/std/ToStringSerializerBase

current version jackson-databind-2.9.10.1.jar
need to upgrade jackson-databind-2.11.1.jar
Run Code Online (Sandbox Code Playgroud)

我在新版本的 jackson 更新 jar 中找不到ToStringSerializerBase

org.springframework.beans.BeanInstantiationException:无法实例化[com.fasterxml.jackson.datatype.jsr310.JavaTimeModule]:无法解析的类定义;嵌套异常是 java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ser/std/ToStringSerializerBase

我发现内部依赖

<dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <version>2.10.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

知道我该如何解决这个问题吗?

swagger-2.0 jackson-databind

6
推荐指数
2
解决办法
6009
查看次数

RestAssured - 无法识别的字段,未标记为可忽略

(注:我已经看到关于“Jackson 抱怨无法识别的属性”主题的多个问题的回答,但我没有找到专门使用 RestAssured 的对象映射器的问题)

我有 RestAssured 测试,它有效

@Test
public void objectMappingRelyingOnClassAnnotation() {

    User user = RestAssured.get("https://api.github.com/users/andrejss88")
            .as(User.class); // must have 'jackson-databind' dependency

    Assert.assertEquals(user.login, "andrejss88");
}
Run Code Online (Sandbox Code Playgroud)

它之所以有效,是因为该类已注释,如下所示

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    public String login;
    public int id;
}
Run Code Online (Sandbox Code Playgroud)

但是,我想使用使用重载方法的替代方法as(),并在不使用注释的情况下传入我自己的映射器:

<T> T as(Class<T> cls, ObjectMapper mapper);
Run Code Online (Sandbox Code Playgroud)

但杰克逊的映射器不起作用:

@Test
public void objectMappingUsingSpecifiedMapper() {

    //  Doesn't compile - Jackson's ObjectMapper != RestAssured's Mapper
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    AnotherUser user = RestAssured.get("https://api.github.com/users/andrejss88")
            .as(AnotherUser.class, objectMapper); …
Run Code Online (Sandbox Code Playgroud)

jackson rest-assured jackson-databind

5
推荐指数
1
解决办法
1981
查看次数

如何编写 Jackson 转换器来处理通用集合类型?

我创建了一个按升序排序的元素,以便生成的 JSON 数组按排序顺序输出,而不是给定实现使用的任意迭代顺序。它按照文档的建议扩展了 Jackson 中的标准类。Jackson ConverterSetSetStdConverterConverter

注意:强烈鼓励实现者扩展StdConverter而不是直接实现Converter,因为这可以帮助典型样板代码的默认实现。

public class OrderedSetConverter
        extends StdConverter<Set<DayOfWeek>, Set<DayOfWeek>> {
    @Override
    public Set<DayOfWeek> convert(Set<DayOfWeek> value) {
        return value == null ? null : value.stream()
                .sorted(Comparator.nullsLast(Comparator.naturalOrder()))
                .collect(Collectors.toCollection(LinkedHashSet::new));
    }
}

public class MyType {
    @JsonSerialize(converter = OrderedSetConverter.class)
    private Set<DayOfWeek> myValues;
}
Run Code Online (Sandbox Code Playgroud)

Converter当要转换特定类型的元素时(在本例中) ,这很有效DayOfWeek。但是,此实现中没有任何特定于特定类型的内容;它对于任何类型都同样有效Comparable。因此,我更希望有一个可用于任何Set可比较的转换器的通用实现。

我尝试通过使用泛型的简单用法来实现这一点:

public class OrderedSetConverter<E extends Comparable<? super E>>
        extends StdConverter<Set<E>, Set<E>> {
    @Override
    public Set<E> convert(Set<E> value) …
Run Code Online (Sandbox Code Playgroud)

java generics jackson jackson-databind

5
推荐指数
1
解决办法
6595
查看次数