user2511713
user2511713

Reputation: 555

Converting JSON to class

and a class named Entry. How can I convert the GlossEntry Object in json to an Entry Class Object in java.

{
    "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"
                }
            }
        }
    }
}

Upvotes: 1

Views: 1709

Answers (2)

Hanan Awwad
Hanan Awwad

Reputation: 63

It depends on platform you are using for the converting; For example using Gson from google needs just tow lines of code, the following example shows how get campaign obj from this json

    String rsou = "{\"name\":\"name\",\"startDate\":\"01/01/2013 00:30\",\"endDate        \":\"01/03*d/2013 12:30\",\"variable\":\"\"}";

    Campaign newCampaign = new Gson().fromJson(rsou, Campaign.class);

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691635

As explained in the "Jackson in 5 minutes" page, which takes 5 minutes to read:

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
Entry entry = mapper.readValue(new File("entry.json"), Entry.class);

EDIT: sorry, I misunderstoof your question. If you want to read a sub-tree of the JSON into a Java object, then read the full JSON as a Tree, then get the sub-tree from the root node, and use ObjectMapper.treeToValue() to transform the sub tree to an Entry Java object. All the steps are described in the page I linked to.

Upvotes: 3

Related Questions