import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import java.io.IOException;
import java.util.List;
public class JsonExample {
public static void main(String[] args) {
String json = "[{\"user\":\"a\", \"extraField\":\"ignoreMe\"},{\"user\":\"b\", \"anotherExtraField\":\"alsoIgnore\"}]";
ObjectMapper mapper = new ObjectMapper();
//mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationConfig.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 这里的TypeFactory用于指定我们想要将JSON解析为哪种类型的集合
CollectionType listType = mapper.getTypeFactory().constructCollectionType(List.class, UserEntity.class);
try {
List<UserEntity> userList = mapper.readValue(json, listType);
for (UserEntity user : userList) {
System.out.println(user); // 输出将只包含user字段的值
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用ObjectMapper解析JSON忽略实体内不存在字段
最新推荐文章于 2025-01-02 14:54:19 发布