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();
}
}
}
07-01
324
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-17
1426
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)