Poyo
Poyo

Reputation: 623

How to convert a JSONobject into an object map?

I’ve been trying to create a dynamic text-grabbing system to be able to translate future programs into different languages more easily. I’m fairly new to Java, so I’m not well versed on the data types that there are, but would it be possible to take a JSON object (using simple.json) and converting it into something that I could reference easily and concisely?

For example given a JSON string:

{
    "name": "John Doe",
    "country": "US",
    "age": 25,
    "family": {
        "immediate": {
            "spouse": "Johnette Doe",
            "children": [
                {
                    "name": "Jimbles Doe",
                    "age": "213"
                }
            ]
        }
    }
}

How could I set my file up so that I could reference it like so:

JohnClass.family.immediate.children[0].name

and get a value in return?

Upvotes: 0

Views: 359

Answers (1)

goncaloGomes
goncaloGomes

Reputation: 163

Get Jackson (either use the maven dependency or download the jar): http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.5.0

Untested code below, and to be honest a effortless punt, just to help you sort it quickly.

Instantiate JSONMapper (ideally in a constructor):

ObjectMapper mapper = new ObjectMapper();

Convert to Hashmap (you could also convert to any other object):

Map map = mapper.readValue("JSON_STRING_HERE", new TypeReference<HashMap>(){});

Access like this:

map.get("family").get("immediate").get("children").get(0).get("name");

You could also just use JSONObject which also implements the Map interface, but if you get used to do it this way you'll know how to do it for other objects.

Upvotes: 1

Related Questions