英文:
Deserializing a HashMap into a POJO and setting empty fields to null?
问题
以下是您要翻译的代码部分:
List<LinkedHashMap> jsonResponse = objectMapper.readValue(jsonResponse, List.class);
for (LinkedHashMap res : jsonResponse) {
ProductsByInstitution resObj = objectMapper.convertValue(res, ProductsByInstitution.class);
}
TypeReference<List<ProductsByInstitution>> typeRef = new TypeReference<List<ProductsByInstitution>>() {};
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
List<ProductsByInstitution> objs = objectMapper.readValue(lambdaResponse, typeRef);
public class ProductsByInstitiution {
private int id;
private String name;
private String status;
private int buy;
private int offer;
private int max;
private int min;
private double figure;
.... (Getters and setters)
}
希望这对您有所帮助。如果您需要更多信息,请随时提问。
英文:
I have a JSON response coming in which I parse as such:
List<LinkedHashMap> jsonResponse = objectMapper.readValue(jsonResponse, List.class);
The JSON response begins with a '{', which is why I have to deserialize it into a List class, and nested in the List are LinkedHashMaps, which I'm not sure if I can directly deserialize into my custom POJO. I'm attempting to convert each HashMap to my custom POJO here:
for (LinkedHashMap res : jsonResponse) {
ProductsByInstitution resObj = objectMapper.convertValue(res, ProductsByInstitution.class);
}
But, this custom POJO has extra optional fields which may or may not be included in the JSON response. What ends up happening is the Integer / Double fields excluded in the JSON response are automatically set to 0 or 0.0, respectively. I want them to be null.
EDIT:
Still receiving 0's for empty fields.
Code I tried:
TypeReference<List<ProductsByInstitution>> typeRef
= new TypeReference<List<ProductsByInstitution>>() {};
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
List<ProductsByInstitution> objs = objectMapper.readValue(lambdaResponse, typeRef);
The last line is where the error is pointing to.
POJO class:
public class ProductsByInstitiution {
private int id;
private String name;
private String status;
private int buy;
private int offer;
private int max;
private int min;
private double figure;
.... (Getters and setters)
So a JSON response might look like this:
id: 0
name: "Place"
status: "Good"
buy: 50
min: 20
Then when deserialization happens, figure, max, and offer are being set to 0 / 0.0
答案1
得分: 0
Primitive type int
or double
can't represent null
. Use wrapper class Integer
or Double
which can represent null value.
public class ProductsByInstitiution {
private Integer id;
private Integer max;
private Double figure;
...
}
英文:
Primitive type int
or double
can't represent null
. Use wrapper class Integer
or Double
which can represent null value.
public class ProductsByInstitiution {
private Integer id;
private Integer max;
private Double figure;
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论