简体   繁体   中英

Correct way to map JSON to Java Object

Im trying to map some json elements to a java object but cant seem to figure out the correct way. Theres obviously loads of examples online on how to map json to pojos but I have a big JSON string and I only want to map a few keys in the JSON String to build up an object...

{
"glossary": {
    "title": "example glossary",
    "GlossDiv": {
        "title": "S",
        "GlossList": {
            "GlossEntry": {
                "ID": "SGML",
                "SortAs": "SGML",
                "GlossTerm": "Standard Generalized Markup Language",
                "Acronym": "SGML",
                "Abbrev": "ISO 8879:1986",
                "GlossDef": {
                    "para": "A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso": ["GML", "XML"]
                },
                "GlossSee": "markup"
            }
        }
    }
}

}

lets say I only want the title and GlossEntry: id, SortAs and Abbrev,

What's the cleanest why to map it to a pojo with only those fields without having to map the whole json to an object and get those elements

If you are open to use Jackson , a popular JSON parser for Java, this answer may give you some insights. Here's a tailored solution for your question.

First define a class as following to hold the values:

@JsonIgnoreProperties(ignoreUnknown = true)
public class GlossaryEntry {

    @JsonProperty("ID")
    private String id;

    @JsonProperty("SortAs")
    private String sortAs;

    @JsonProperty("Abbrev")
    private String abbrev;

    // Constructor, getters and setters omitted
}

Then parse the whole JSON into a JsonNode with ObjectMapper :

String json = "{\"glossary\":{\"title\":\"example glossary\",\"GlossDiv\":{\"title\":\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\",\"SortAs\":\"SGML\",\"GlossTerm\":\"Standard Generalized Markup Language\",\"Acronym\":\"SGML\",\"Abbrev\":\"ISO 8879:1986\",\"GlossDef\":{\"para\":\"A meta-markup language, used to create markup languages such as DocBook.\",\"GlossSeeAlso\":[\"GML\",\"XML\"]},\"GlossSee\":\"markup\"}}}}}";

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);

Use JSON Pointer to query for the GlossEntry node and finally use ObjectMapper to parse it into a GlossaryEntry instance:

JsonNode node = tree.at("/glossary/GlossDiv/GlossList/GlossEntry");
GlossaryEntry glossaryEntry = mapper.treeToValue(node, GlossaryEntry.class);

JSON Pointer is a path language to traverse JSON. For more details, check the RFC 6901 . It is available in Jackson since the version 2.3.

With googles gson library you can map the json to a generic JsonElement. From there you can access fields and traverse subobjects as you like.

JsonElement elem = new JsonParser.parse(input);

This gets more complicated the more fields you require. I'd suggest building a deserialization DTO providing the right object hierarchy. You can then use standard mapping approaches to map your json. In a second step you can map this DTO to your own domain model. Projects like ModelMapper make this task fairly easy.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM