This is the JSON I’m working on:
{
"default": "ignore-me",
"catalog": [
{
"id": "object-1",
"name": "Object 1"
},
{
"id": "object-3",
"name": "Object 3"
},
{
"id": "object-2",
"name": "Object 2"
}
]
}
I can parse it in Java using Jackson with:
ObjectMapper mapper = new ObjectMapper();
Catalogs catalogs = mapper.readValue(new File("/catalogs.json"), Catalogs.class);
Java model for Catalogs.java
and Catalog.java
:
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class Catalogs {
@JsonProperty("default")
private String defaultField;
private List<Catalog> catalogList;
// getters / setters
}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Catalog {
private String id;
private String name;
// getters / setters
My goal is to convert List<Catalog> catalogList
into something like a HashMap
which allows for quicker access to entries when the id
is known ahead of time, rather then having to iterate through all entries.
So I’d like to do something like:
Catalog catalog = catalogs.getCatalogList().get("object-1");
Is it possible for Jackson to do this conversion of type automatically during deserialization?
3
Answers
You need to create getter/setter and convert to/from map there. Also provide getter for map.
Custom Deserializer Solution
If you want to deserialize a
List
ofCatalog
as aHashMap
, you could define a custom deserializer extending theStdDeserializer
class and annotate the fieldcatalogs
with the@JsonDeserialize
annotation. The deserialzer will be responsible for converting theList
structure to aMap
according to your logic.Custom Serializer to maintain List structure in Json
Furthermore, assuming that you want to maintain the same list structure within the json, and therefore not serializing
catalogs
as aMap
but still as aList
, you need to define a custom serializer as well. In the custom serializer class, you would basically implement the opposite logic of the other class, i.e. creating aList
from a givenMap
, and serialize it as an array ofCatalog
elements. Thecatalogs
field must be annotated with the@JsonSerialize
annotation.Catalogs Pojo
Demo
Here is a demo at OneCompiler.
One possible solution is to using Jackson to parse the JSON into JsonNode first. Then use another JSON library to perform re-structure before converting it to POJO.
https://github.com/octomix/josson
Revised Class
Catalogs
Josson function:
field()
modify a field with new valuemap()
construct new object, syntaxid::?
retrieve the value ofid
to become the key name and?
denote the current nodemergeObjects()
merge all objects inside an array to build a new objectOutput