在Jackson中将内部JSON对象提取为String [英] Extract the inner JSON object as String in Jackson

查看:98
本文介绍了在Jackson中将内部JSON对象提取为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用杰克逊反序列化以下JSON对象.

I would like to deserialize the following JSON object using Jackson.

[
    {
      "_foo": "foo-value",
      "_bar": {// bar json object }
    },
    {
      "_foo": "foo-value",
      "_bar": {// bar json object }
    }
]

我不在乎 bar JSON对象,因此我只想将其解析为String.这是我的Pojo课堂的样子:

I don't care about the bar JSON object so I just want to parse it as String. Here is how my Pojo class looks like:

@Data
public class Document {

  @JsonProperty("_foo")
  private String foo;

  @JsonProperty("_bar")
  private String bar;
} 

当我尝试使用Jackson和以下代码对对象进行反序列化时.它引发异常.

When I try to deserialize the object using Jackson with the following code. It throws an exception.

List<Document> docs = mapper.readValue(fileContent, new TypeReference<List<Document>>() {
        })

例外:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token

我做错了什么?

推荐答案

如果您不在乎,则可以忽略此属性:

If you don't care then you can ignore this property:

@Data
@JsonIgnoreProperties(value = {"_bar"})
public static class Document { ...

或者您可以使用JsonNode添加setter:

or you can add setter with JsonNode:

    @JsonProperty("_bar")
    private String bar;

    @JsonSetter
    private void setBar(JsonNode jsonNode) {
        this.bar = jsonNode.toString();
    }

    private void setBar(String bar) {
        this.bar = bar;
    }

或使用JsonNode作为字段:

or use JsonNode as field instead:

    @JsonProperty("_bar")
    private JsonNode bar;

这篇关于在Jackson中将内部JSON对象提取为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆