I'm looking for a way to directly convert some POJO to a Jackson TreeModel. I know that a translation from POJO-to-JSON-String exists, and TreeModel-to-JSON-String is supported — hovewer I am looking for a POJO-to-TreeModel translation. Is there a way?
The use-case is as follows:
Server-side templating is done with the Java implementation of Mustache. This uses Jackson's TreeModel.
After that, I need a slimmed-down version of the TreeModel on the client-side, so I want to be able to first filter the TreeModel, serialize that to JSON, then send it to the client-side for further processing.
This, ideally, involves two serialization steps. However, in my workaround, I am currently using three — which you can see here:
map = // a map of pojos with jackson annotations
//pojo >> JSON
StringWriter w = new StringWriter();
objectmapper.writeValue(new JsonFactory().createJsonGenerator(w), map);
String json = w.toString();
w.close();
//JSON >> Treemodel
JsonNode tree = GenericJcrDTO.mapper.readTree(json);
//filter tree here
//treemodel >>JSON
StringWriter w = new StringWriter();
GenericJcrDTO.mapper.writeValue(new JsonFactory().createJsonGenerator(w), tree);
json = w.toString();
w.close();
Anyone?
To answer my own question:
JsonNode node = objectMapper.valueToTree(map);
Related
I have a project where I need to support serialising model classes to JSON using both Jackson and GSON (switchable).
Besides simply converting these model classes to JSON I also need to manipulate the by adding/removed certain keys (as per user input).
I was thinking of converting my model classes (and the logic to remove/add data) to simple java.util.Maps and convert these to JSON. Which works.
To convert these model classes to the java.util.Maps for Jackson I'm doing:
Map<String, Object> jsonMap =
mapper.convertValue(object, new TypeReference<Map<String, Object>() {})
and for GSON:
JsonElement jsonElement = gson.toJsonTree(object);
Map<String, Object> jsonMap =
gson.fromJson(jsonElement, new TypeToken<Map<String, Object>>(){}.getType());
After manipulating the data in the map, I do the following to actually serialize the map to JSON string:
// Jackson
mapper.writeValueAsString(jsonMap);
// GSON
gson.toJson(jsonMap);
Is there a performance hit to convert a model Object to a Map instead of a Jackson JsonNode (mapper.convertValue(object, ..) vs. mapper.valueToTree(object))?
Would it be possible to directly convert a model Object to a Map using GSON? Now I'm first creating a JsonElement and then converting it to a Map.
Jackson's ObjectNode uses LinkedHashMap internally (and ArrayNode uses ArrayList), so there should not be much difference between these approaches. JsonNode model can optimize some things slightly better than "raw" Lists and Maps; but on the other hand there is thin wrapper that adds some memory usage... so in the end things probably even out.
I would like to de-serialize a JSON string and conduct object mutations including replicating nodes, adding new nodes to arrays, and changing the value of text nodes. I read that JsonNodes are for reading and ObjectNodes are for editting.
The only thing I could find to attempt was:
root = mapper.readTree(apiResponseTemplate);
ObjectNode rootTwo = mapper.valueToTree(root);
I'm using jackson 1.9.12
How can I do this? Thanks!
To parse the JSON string you could use something like this.
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonText);
To add new nodes:
ObjectNode objNode= mapper.createObjectNode();
objNode.put("NodeName", "NodeValue");
To add new ArrayNodes:
objNode.putArray("NodeName");
JsonNode has many useful methods like has("NodeName"), path("NodeName"), etc.
I have seen the responses from many other posts but would like to understand if there is a better way to do the same thing.
Requirement:-
I am using restTemplate to talk to web service which returns JSON output which is dynamic. As a consumer I don't want to access all fields but is interested in few of them. I am using Spring framework with Jackson parser and found the way of accessing it
String response = restTemplate.getForObject(targetUrl, String.class);
System.out.println(response);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(response, JsonNode.class);
JsonNode uri = rootNode.get("uri");
System.out.println(uri.asText());
Do you know any better way to do it? Mapping to java Object is something that I dont want to do as the json output is not in my control
If your RestTemplate is configured with the default HttpMessageConverters, which is provided by Jackson2ObjectMapperBuilder, you may directly get a JsonNode from restTemplate.getForObject.
For example,
ArrayNode resources = restTemplate.getForObject("/resources", ArrayNode.class);
Or,
ObjectNode resource = restTemplate.getForObject("/resources/123", ObjectNode.class);
Note that ArrayNode and ObjectNode are sub-classes of JsonNode.
I need to pass a map back to the web application.
I'm used to encapsulating the map in a JSONObject
http://json.org/java/
But since I am using Spring and Jackson Haus.
is there an easier way to maintain the pojo? May I can just annotate the MAP ?
Jackson has com.fasterxml.jackson.core.JsonNode, and specific subtypes like ObjectNode.
These form so-called Tree Model, which is one of 3 ways to handle JSON with Jackson -- some other libraries (like org.json) only offer this way.
So you should be able to just use JsonNode instead; there is little point in using org.json library; it is slow, and has outdated API.
Alternatively you can just use java.util.Map, and return that. Jackson can handle standard Lists, Maps and other JDK types just fine.
If you need to manipulate the output, ie, you don't want to provide all the fields of the object you can use JSonArray:
#RequestMapping(value = "/api/users", method = RequestMethod.GET)
public
#ResponseBody
String listUsersJson(ModelMap model) throws JSONException {
JSONArray userArray = new JSONArray();
for (User user : userRepository.findAll()) {
JSONObject userJSON = new JSONObject();
userJSON.put("id", user.getId());
userJSON.put("firstName", user.getFirstName());
userJSON.put("lastName", user.getLastName());
userJSON.put("email", user.getEmail());
userArray.put(userJSON);
}
return userArray.toString();
}
Use the example from here
Otherwise if you add jackson to your dependencies and set the controller method anotatted with #ResponseBody the response will automatically mapped to JSON. Check here for a simple example.
I have all the POCO entities produced from my database. I created an IXXX interface, a XXX class to define the structure of the table I want to return from my service, and a XXX class to do the query and the return part for the interface.
My question is regarding the elements I need to add to this setup in order to return clean JSON from my web service.
I'm a beginner so all points of view are welcome. Thanks!
You can define XXXDto classes which are having a clean format for your client needs. And then map the domain/endity classes to Dto objects and serialize them using WCF.
Or you can create WCF OData services to expose the service as OData source.
try this:
To return Json data [in EF]:
add reference 'System.Runtime.Serialization' to the project
write code like below:
using System.Web.Script.Serialization;
public string getValuesJson()
{
JavaScriptSerializer js = new JavaScriptSerializer();
MyDBEntities ctx = new MyDBEntities();
var myValues = (from m in ctx.TestEntity
where (m.id == 22)
select m).ToList();
return js.Serialize(myValues);
}
you can also check whether Json string is valid or not at http://jsonlint.com/