Use Jackson to create simple objects like JSON.org

I want to use Jackson to create simple JSON objects, where I do not need to create custom classes for each response, but rather a ready-made 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 cannot find a similar operation in Jackson packages. PS : I know that I can create a java class to encapsulate this particular JSON string, but what I'm looking for is a way to create shared JSON objects that I DO NOT need to parse in the classes that I defined, It seems I can't find something on the internet that points me to something like this. I have a feeling that this is outside the Jackson zone, and they do not support such operations. If so, just say it and I will close the question.

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


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

Here is a sample code:

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

Sounds like you need a Map . If you have a simple JSON structure, you can use Map<String, String> like this:

 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 objects and what not, you can use 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 .

+4
source

Source: https://habr.com/ru/post/956686/


All Articles