So I consume data from a REST endpoint (which I don't have access to) that is badly formatted.
In particular, I receive a json object that actually is a list. What is the best way to deal with this? Can it be done with Jackson?
{
"list": {
"element 31012991428": {
"objId": 31012991428,
"color": "green"
},
"element 31012991444": {
"objId": 31012991444,
"color": "orange"
},
"element 3101298983": {
"objId": 3101298983,
"color": "red"
},
}
}
Ideally, I want to be able to parse it as follows:
Response.java
public class GetSucherResponse {
@JsonProperty("elements") //what goes here?
private List<Element> elements;
}
Element.java
public class Element {
@JsonProperty("objId")
private Long objId;
@JsonProperty("color")
private String color;
}
Created a rough solution
Response class should look like:
@JsonDeserialize(using = ResponseDeserializer.class)
public class Response {
private List<Element> elements;
public Response(List<Element> elements) {
this.elements = elements;
}
}
Deserializer:
public class ResponseDeserializer extends StdDeserializer<Response> {
protected ResponseDeserializer() {
super(Response.class);
}
@Override
public Response deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
TreeNode rootNode = jsonParser.getCodec().readTree(jsonParser);
TreeNode listNode = rootNode.get("list");
List<Element> elements = new ArrayList<>(listNode.size());
listNode.fieldNames().forEachRemaining(
s -> elements.add(parseElement(jsonParser, listNode.get(s)))
);
return new Response(elements);
}
private Element parseElement(JsonParser jsonParser, TreeNode subNode) {
Element element = null;
try {
element = jsonParser.getCodec().treeToValue(subNode, Element.class);
} catch (JsonProcessingException e) {
e.printStackTrace(); //TODO handle it in a better way
}
return element;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.