java - 如何正确映射 JSON 对象?
问题描述
这是我的代码:
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObjectMapperJSON {
public static void main(String[] args) throws IOException, JsonParseException, JsonMappingException {
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonString = "{\"numberOFiles\":13, \"filename\":\"123.jpg\"}";
/* int temp = Integer.parseInt(jsonString);
*/ ObjectMapper objectMapper = getObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try{
JsonBean JsonBean = mapper.readValue(jsonString, JsonBean.class);
System.out.println(JsonBean);
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JsonBean);
//jsonString = mapper.writeValueAsString(JsonBean);
System.out.println(jsonString);
}
catch (Exception e){
e.printStackTrace();}
}
}
输出结果是: Filename [ filename: 123.jpg, numberOfFiles: 0 ] { "filename" : "123.jpg", "numberOfFiles" : 0
所以我的问题是为什么 numberOfFiles 的值打印为 0?调试向我显示直到最后一个 syso 的值为 13。如何正确执行此操作?
解决方案
您的 json 字符串中有错字。更新numberOFiles
到numberOfFiles
.
推荐阅读
- javascript - 当我尝试使用 mocha 运行 npm test 时,在我的 cmd 中显示“错误:找不到模块'路径'”有人知道如何解决这个问题吗?
- .net - EF 提供程序特定模型配置(如果为 true,则需要)
- sql - 将连接与条件聚合一起使用
- java - ByteBuddy:无法访问类变量
- c# - 从字典中获取,它是 Object 的一个实例
- windows - 如何在 windows 上获取 wsChromeEndpointUrl
- node.js - 如何自定义存储在 winston 记录器文件中的错误
- angular - 导入内部函数返回 ZoneAwarePromise
- c# - 使用 jquery 和 timepicker
- firebase - 收款组查询的 Firestore 计费