How to Convert String to Dataset - java

I am getting a value in Json Format and Assigned it into a String.
In Java, How can i Convert a String Value into a Data Set of Ignition. And
how do i Convert a Json Object to Data Set?
postRequest.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
ObjectMapper mapper = new ObjectMapper();
HttpEntity entity;
entity = new StringEntity(mapper.writeValueAsString(context), ContentType.APPLICATION_JSON);
postRequest.setEntity(entity);
CloseableHttpResponse httpResponse = null;
httpResponse = httpClient.execute(postRequest);
String response = null;
response = EntityUtils.toString(httpResponse.getEntity());
AnalysisData = response;
Dataset dataset = Dataset.class.cast(vAnalysisData);

Java does not handle Json parsing on it's own. You must import a third party Json library. Google Gson is the one I use. Here is the link. Once the Json response is parsed into Json Elements, then you can add each element to the DataSet.
Share part of your code, so that it will be easier to help.

Related

InputStream does not seem to read response objects in list

I am trying to read a response from an API endpoint. It works in Postman and appears to work when debugging my java code.
However it will not read any objects that are in the nested array.
I've followed this solution (in the comments someone lays out their solution to accessing objects in a nested array) yet that does not seem to have solved anything as the mapper consistently shows nothing inside the json list.
Here's my code:
try {
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(inputStream);
final JsonNode value = node.get("value");
final JsonNode index = value.get(1);
final String status = index.get("status").asText();
return status;`
}
Here's the response that I'm trying to unpack. I'm trying to get the value of "status"
{
"value": [
{
"activityRunEnd": "2023-01-23T23:22:01.4234985Z",
},
{
"status": "Succeeded"
}
]
}
This is the response that I'm currently getting when I readTree(inputStream)
{"value":[]}
InputStream does not seem to read any values inside the list

Store request body as JSON into the database - Java

I want to store the request body into the database. I am storing the headers and request into the audit trail table.
For conversion of headers, I am creating a map and then storing the json into the database like this:
String method = httpServletRequest.getMethod();
Enumeration<String> values = httpServletRequest.getHeaderNames();
Map<String,String> headers = new HashMap<String, String>();
while (values.hasMoreElements()) {
String key = values.nextElement();
String innerValue = (String)httpServletRequest.getHeader(key);
headers.put(key,innerValue);
}
// converting object to Array
auditTrail.setHeaders(appUtility.objectToString(headers));
How can I store the request body as json into the database (ignore files for now)? The request body can be one object, array of objects or a combination.
Right now, I have written an ASPECT which will store all the incoming requests into the database. It's easy to store the json of the object when I know the Object but how can we make it generic?
If you know that content is JSON and want to read data from stream you can do it on this way:
String jsonBody = request.getReader().lines()
.collect(Collectors.joining(System.lineSeparator()));
If you need to validate is jsonBody really JSON you can use Jackson:
public static boolean isJSONValid(String jsonInString ) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
If you have a body as the object you can use Jackson.
Example:
SomeObject body = ...; // Your body
ObjectMapper objectMapper = new ObjectMapper();
String bodyAsString = objectMapper.writeValueAsString(body); // To JSON
body = objectMapper.readValue(bodyAsString, SomeObject.class); // From JSON
Jakson with maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

how to print Original request body JSON without any modification in java?

Normally to print out request body i using ObjectMapper, but this way removing space and printing object to string in one line, example :
if i send request body like this :
{
"Header" : "value"
}
and i using objectMapper to print that object
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(requestBody)
the out put is like this :
{"Header":"value"}
how to print Original request body without any modification ?
I'm not sure if you can print it in it's original form but you can pretty print it.
With Jackson's Object Mapper, you can do something like:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
System.out.println(json);
or
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(body);
System.out.println(json);
I don't think you can do this without using any framework.
But you can use the gson for this if you enable the prettyPrinting option. Example:
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
prettyPrintedString = gson.toJson(requestBody, Object.class);

How to properly get the body of a WebTarget get request response (JAX-RS)?

How do i get the body of a HTTP get request with the javax.ws.rs library?
I tried:
Response response = service.path(path).request().get();
String body = response.readEntity(String.class);
but that doesn't work. Instead i get this exception: java.lang.NoClassDefFoundError: javax/ws/rs/core/NoContentException
Then i tried:
Response response = service.path(path).request(MediaType.APPLICATION_JSON_TYPE).get();
String body = response.readEntity(JSONObject.class);
because I should actually get a JSON String back but i don't need it as JSON Object, that's the reason why i tried it like above before.
But that doesn't work at all, i even can't compile and get the (IntelliJ) message
no instance(s) of type variable(s) exist so that JSONObject conforms to String inference variable T has incompatible bounds: equality constraints: JSONObject upper bounds: Object, String
Addition:
I get 200 as response status so everything worked fine and when i do the same in e.g. Postman or Fiddler it works.
You can do this by using Jackson: first you create object from body
ObjectMapper mapper = new ObjectMapper();
InputStream responseBody = response.getBody().in();
JSONObject jsonobject = mapper.readValue(responseBody, JSONObject.class);
Then transform jsonobject to string:
String jsonInString = mapper.writeValueAsString(jsonobject);
In this specific case it should also work with
Response response = service.path(path).request(MediaType.APPLICATION_JSON_TYPE).get();
String body = response.readEntity(String.class);
because it tries to read the Entity and construct an object of the given type out of it. So I think that should work.

invoke rest api with array of string

[
['a','b','c','d','e','f','g'],
['a1','b1','c1','d1','e1','f1','g1'],
['a2','b2','c2','d2','e2','f2','g2'],
['a3','b3','c3','d3','e3','f3','g3']
]
I have above string, have converted to json object as:
JSONObject json = new JSONObject();
json.put("name", "a");
json.put("country", "b");
json.put("state", "c");
...
...
HttpPost post = new HttpPost(url);
...
HttpResponse httpresponse = client.execute(post);
This works fine for me.
My question is instead of above code, i,e creating json object and sending, can I directly pass the string to my rest component? If possible, what type of mime I need to select?
Requirement is pass the entire string and split in backend java component instead of split, convert to json then send to back end.
The MIME media type for JSON text is application/json. The default encoding is UTF-8. (Source: RFC 4627).

Categories