how to get the JSON out of the jackson ObjectMapper - json

We need to bulid up a json payload to send to a rest endpoint. Our org uses Jackson. The only way to build up the json (without creating dozens of nested empty pojos) is as follows:
ObjectMapper mapper = new ObjectMapper();
ObjectNode rootNode = mapper.createObjectNode();
ObjectNode content = mapper.createObjectNode();
rootNode.set("someContent", content);
content.put("somekey","someval");
... lots more nested objects created here...
Ok, so now I have a complex json object in the mapper. How do I get it out?
E.g. How do I get a json string out of it suitable for sending to an REST api as post payload?
There are various examples of setting up pretty print, but these revolve around jsonizing a single java object (which I am not doing), or outputting to streams or files, not a simple String.
Any suggestions?

perhaps use ObjectMapper.writeValueAsString:
System.out.println(mapper.writeValueAsString(rootNode));

Related

Kafka streams API - deserialize dynyamically generated JSON

I've been trying to find a solution to the following situation with no avail:
I have a Kafka Streams application which should read from a single input topic a series of JSON objects, all not exactly the same as one another. Practically speaking, each JSON is a representation of an HTTP request object, thus not all JSON records have the same headers, request parameters, cookies and so forth. Furthermore, the JSON objects are written
Is there any way to achieve this? Not expecting for any detailed how-to solutions. Only for some leads on how I can achieve this, as my search over the internet has ended me with nothing so far.
Here's an idea: use Jackson's tree model to dynamically parse your JSON into a JsonNode, and then use this tree representation in your Kafka Streams topology to process the requests.
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(json);
...

Jersey Web Service

I am using Jersey Rest Service. I am getting clients requests in json and getting java object out of it. Everything works fine. However, is there anyway I can get the exact json that was pass from client without even converting to java object.
Issue is json request contents just two parameters and below ObjectMapper converts back to Json but with null values. To ignore, I have to put #JsonInclude(Include.NON_NULL) on each pojo class. If I can get just client json, then it would be good.
ObjectMapper mapper=new ObjectMapper();
String jsonString= mapper.writeValueAsString(body);
Keep the following in your resource method:
#Consumes("application/json")
public Response fn(String payload){} //Notice the payload of type string.
That way the payload will be just a String. I am still not sure why you want it this way, but it should work.

Efficient way of parsing Jax-ws Restful Response

I need to parse the jax-ws rest response and I tried the following two ways of parsing the response.Both works good.But I am in need to know the best efficient way of implementation.Please provide me your view.
First Approach:
Use getEntity Object and get the response as Input Stream.
Using Jackson ObjectMapper readValue() -covert the inputstream to java
object.
Using getters and setters of nested java class get the response objects member values.
Second Approach:
Use getEntity Object and get the response as Input Stream and and
convert the Input Stream to String.
Using Google Json API,convert the string to json object.
Using Json parser and get the nested objects member values.
I would say the first approach is better for two reasons:
You don't go through the intermediate process of reading the response payload into String
The setter methods that are called during Jackson deserialization may perform validation on input and throw appropriate exceptions, so you do validation during deserialization.
Maybe not a general answer to this question but another variant of what you're describing under "First approach". I would start with a generic data structure and would only introduce an extra bean if necessary. I wouldn't use String to pass structured data around.
Use jackson to convert the JSON response to a
Map<String,Object> or JsonNode.
Advantage:
You don't need to implement a specialized bean class. Even a very simple bean can become unhandy over time (if format changes or new nested structures are added to the json response, etc.). It also introduces some kind of metaphor to your code which sometimes helps but also can be misleading.
Map<String,Object> is in the JDK and offers a good interface to access data. You don't have to change any interfaces even if the JSON format changes.
You can always pass your data in form of a Map<String,Object>
Disadvantage
Data Encapsulation. The map is a very close representation of the input data and therefore offers not same level of abstraction like a bean.

How to Intercept parameters sent as JSON data in HTTPRequest to Controller?

We are in the process of building a custom built JEE security layer which is going to ensure that all possible OWASP concerns are addressed. This security layer is built as Filters that needs to run before the Controllers (Spring in our case), so that they can execute before the request actually reaches the Controller. These security filters looks at the user input and performs various Sanitation. One such sanitation is the JSON sanitation, where the JSON data from client is looked for any malicious content.
Currently , the Spring Controllers use the #RequestBody annotation to populare the incoming JSON data into POJO classes.
I have exactly the same question but, is there a generic way to retrieve the parameters (sent as JSON data) from the request ?
my objective is to have a JSON sanitizer code in a Filter, so that it
intercepts and parses all JSON data that comes to the controller.
I was able to read & retrieve the json data using the following technique. The StringBuffer jb finally has the entire JSON data.
StringBuffer jb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
}
Ref: HttpServletRequest get JSON POST data

Way to Consume Json request as Json object in Jersey Rest Service

Hi I tried googling around but cannot find solution that I want to achieve.
Example to map json to java object we do
#POST
#Consumes(application/json)
#Produces(application/json)
public Response createUpdateDeleteManualClinicalData(MyJavaPojo definedPojo) {
// this maps any json to a java object, but in my case I am dealing with generic json structure
}
What I want to achieve is Keep it as json object itself
public Response createUpdateDeleteManualClinicalData(JSONObject json)
Work around: I can get data as plain text and convert that to json. But its an overhead from my side which I want to avoid.
Edit: I am open to using any Json library like JsonNode etc... as far as I get Json object Structure directly without the overhead of String to Json from my side. This should be common usage or am I missing some core concept here.
It was a straight solution that I happened to overlooked... my bad.
Jersey is way smarter than I thought... curious to know what magic happens under the layers
#POST
#Consumes(application/json)
#Produces(application/json)
public Response createUpdateDeleteManualClinicalData(JsonNode jsonNode) {
//jsoNode body casted automatically into JsonNode
}
What is the web.xml configuration you are using? Is it something similar to here web.xml setup gists for Jersey1 and Jackson2?
If you are using the same configuration as web.xml setup gists for Jersey1 and Jackson2, then you may do as below. This is a possible alternative than using JSONObject
#POST
#Path("/sub_path2")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Map<String,Object> saveMethod( Map<String,Object> params ) throws IOException {
// Processing steps
return params;
}