ug_
ug_

Reputation: 11440

Use Jackson to create simple objects like JSON.org

I want to use Jackson to create simple JSON objects where I am not required to build custom classes for every response but rather a premade object similar to the code below. Other JSON libraries (android, JSON.org, GSON) you can do something similar to this

JsonObject myObject = new JsonObject("{\"a\":1}");
myObject.getInt("a"); // returns 1

I cant seem to find a similar operation in the Jackson packages. PS: I know I can create an java class to encapsulate this specific JSON string but what I am looking for is a way to create generic JSON objects that I DONT need to parse into a classes that I have defined. I cant seem to find anything on the internet that points me to something similar to this. I have a feeling this is outside Jacksons realm and they do not support operations like this. If this is the case just say so and I will close the question.

My goal is to not have another Json library in my project.


Edit 2014: I found you can use the class org.codehaus.jackson.node.ObjectNode that will hold your object and allow you to do operations as described in my question.

Heres a code sample:

ObjectMapper mapper = new ObjectMapper();
ObjectNode myObject = (ObjectNode) mapper.readTree("{\"a\":1}");
System.out.println(myObject.get("a").asInt()); // prints 1

Upvotes: 6

Views: 6691

Answers (1)

Boris the Spider
Boris the Spider

Reputation: 61148

Looks to me like you need a Map. If you have a simple JSON structure then you can use a Map<String, String> like so:

String json = "{\"name\":\"mkyong\", \"age\":\"29\"}";
Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();
try { 
    //convert JSON string to Map
    map = mapper.readValue(json, 
        new TypeReference<HashMap<String,String>>(){});
    System.out.println(map);
} catch (Exception e) {
    e.printStackTrace();
}

If you have a more complex JSON structure with nested objets and what not, then you can use a Map<String, Object>:

ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
    new File("c:\\user.json"),
    new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
@SuppressWarnings("unchecked")
ArrayList<String> list = (ArrayList<String>) map.get("messages");

Examples taken from the ever useful Mkyong.com.

Upvotes: 4

Related Questions