我需要将某个JSON字符串转换为Java对象。我正在使用Jackson进行JSON处理。我无法控制输入JSON(我从web服务读取)。这是我的输入JSON:

{"wrapper":[{"id":"13","name":"Fred"}]}

下面是一个简化的用例:

private void tryReading() {
    String jsonStr = "{\"wrapper\"\:[{\"id\":\"13\",\"name\":\"Fred\"}]}";
    ObjectMapper mapper = new ObjectMapper();  
    Wrapper wrapper = null;
    try {
        wrapper = mapper.readValue(jsonStr , Wrapper.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("wrapper = " + wrapper);
}

我的实体类是:

public Class Student { 
    private String name;
    private String id;
    //getters & setters for name & id here
}

我的Wrapper类基本上是一个容器对象来获取我的学生列表:

public Class Wrapper {
    private List<Student> students;
    //getters & setters here
}

我一直得到这个错误和“包装器”返回null。我不知道少了什么。有人能帮帮我吗?

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
    Unrecognized field "wrapper" (Class Wrapper), not marked as ignorable
 at [Source: java.io.StringReader@1198891; line: 1, column: 13] 
    (through reference chain: Wrapper["wrapper"])
 at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
    .from(UnrecognizedPropertyException.java:53)

当前回答

这个解决方案在读取json流时是通用的,只需要获取一些字段,而在域类中没有正确映射的字段可以忽略:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)

一个详细的解决方案是使用jsonschema2pojo等工具来自动生成所需的域类,例如从json响应的Schema中生成Student。您可以通过任何在线json到模式转换器来实现后者。

其他回答

新的Firebase Android引入了一些巨大的变化;文档副本下面:

[https://firebase.google.com/support/guides/firebase-android]:

更新您的Java模型对象

和2一样。x SDK, Firebase Database会自动将传递给DatabaseReference.setValue()的Java对象转换为JSON,并可以使用DataSnapshot.getValue()将JSON读入Java对象。

在新的SDK中,当使用DataSnapshot.getValue()将JSON读入Java对象时,JSON中的未知属性现在默认被忽略,因此您不再需要@JsonIgnoreExtraProperties(ignoreUnknown=true)。

为了在将Java对象写入JSON时排除字段/getter,注释现在被称为@Exclude而不是@JsonIgnore。

BEFORE

@JsonIgnoreExtraProperties(ignoreUnknown=true)
public class ChatMessage {
   public String name;
   public String message;
   @JsonIgnore
   public String ignoreThisField;
}

dataSnapshot.getValue(ChatMessage.class)

AFTER

public class ChatMessage {
   public String name;
   public String message;
   @Exclude
   public String ignoreThisField;
}

dataSnapshot.getValue(ChatMessage.class)

如果JSON中有一个Java类之外的额外属性,你会在日志文件中看到这样的警告:

W/ClassMapper: No setter/field for ignoreThisProperty found on class com.firebase.migrationguide.ChatMessage

您可以通过在类上添加@IgnoreExtraProperties注释来消除此警告。如果你想让Firebase数据库的行为,因为它在2。如果有未知的属性,你可以在类上放一个@ThrowOnExtraProperties注释。

你可以使用Jackson的类级注释:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties

@JsonIgnoreProperties
class { ... }

它将忽略POJO中未定义的所有属性。当您只是在JSON中寻找几个属性而不想编写整个映射时,这非常有用。更多信息请访问杰克逊的网站。如果你想忽略任何未声明的属性,你应该这样写:

@JsonIgnoreProperties(ignoreUnknown = true)

根据这个文档,你可以使用Jackson2ObjectMapperBuilder来构建你的ObjectMapper:

@Autowired
Jackson2ObjectMapperBuilder objectBuilder;

ObjectMapper mapper = objectBuilder.build();
String json = "{\"id\": 1001}";

默认情况下,Jackson2ObjectMapperBuilder禁用错误unrecognizedpropertyexception。

FAIL_ON_UNKNOWN_PROPERTIES选项默认为true:

FAIL_ON_UNKNOWN_PROPERTIES (default: true)
Used to control whether encountering of unknown properties (one for which there is no setter; and there is no fallback "any setter" method defined using @JsonAnySetter annotation) should result in a JsonMappingException (when enabled), or just quietly ignored (when disabled)

你可以使用

ObjectMapper objectMapper = getObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

它将忽略所有未声明的属性。