Using JSON data as a String object in Java - java

I am using HTTP Client to send different kinds of requests (GET, PUT, POST, DELETE) where I am sending the JSON as a data to post with different requests.
I have a JSON data like:
{ "createdByID": "100000", "createdByName": "Admin", "modifiedByID": "100000", "modifiedByName": "Admin" }
Now, to store this JSON into a string, I have to add double quotes wherever necessary so that this can be stored as
String jsonData = "{" + "\"" + "createdByID" + "\"" + ":" + "\"" + "100000" + "\"" + "," + "\"" + "createdByName" + "\"" + ":" + "\"" + "Admin" + "\"" + "," + "\"" + "modifiedByID" + "\"" + ":" + "\"" + "100000" + "\"" + "," + "\"" + "modifiedByName" + "\"" + ":" + "\"" + "Admin" + "\"" + "}"
Does anyone use any tool/utility to convert the JSON data such that it can be stored in a string object?
Please share if anyone has already done this

Hey if you store the json as a sting in your code then only you need to add double codes.
Try to read json from a text file , then you don't need to add double quotes and other stuffs.
More over java does not consider double quotes after compiling your code.

Related

Unable to get value from redis using webflux

Currently I am storing some value in redis
And when I try to get the value I am getting MonoNext
This is the code
redisOps.opsForValue().set(sId + "_" + cId + "_" + sufix, true);
Mono<String> data = redisOps.opsForValue().get(sId + "_" + cId + "_" + sufix);
I am expecting it to be of Mono<String>.
Is there something wrong here?

Reading element one by one in JsonArray

I have below JSON returned by API call.
String jsonString="{\r\n" +
" \"count\": 100,\r\n" +
" \"limit\": 100,\r\n" +
" \"totalResults\": 225,\r\n" +
" \"hasMore\": true,\r\n" +
" \"items\": [\r\n" +
" {\r\n" +
" \"id\": \"55D40522-8672-48B0-B225-FD3CE6686AD6\",\r\n" +
" \"name\": \"AcmeHCMExtended\",\r\n" +
" \"version\": \"20.01.01.03\",\r\n" +
" \"status\": \"DRAFT\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"id\": \"2DB4C83B-0CF9-4A8E-AC41-A29B30324121\",\r\n" +
" \"name\": \"AFinancialBot\",\r\n" +
" \"version\": \"1.0\",\r\n" +
" \"status\": \"DRAFT\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"id\": \"7EA85B81-3CA1-4BE0-B095-217E7C93DCEF\",\r\n" +
" \"name\": \"AIAMFG\",\r\n" +
" \"version\": \"1.0\",\r\n" +
" \"status\": \"DRAFT\"\r\n" +
" }"
I want to read name one by one under the itmes. I am using below code.
JsonObject obj=Json.parse(jsonString).asObject();
JsonArray items=obj.get("items").asArray();
System.out.println(items); //it prints everything under items.
`System.out.println(items.name); ` //It gives error
I am not able to iterate item array. it does not show length property of array.
Can you guide me how can I access element one by one.
It looks like you are using the javax.json.JsonArray APIs or something similar. If so:
JsonArray items = obj.get("items").asArray();
for (int i = 0; i < items.size(); i++) {
System.out.println(items.getJsonObject(i));
}
Note that JsonArray implements java.util.List and you are getting the size using the standard List API method.
The same code would work with com.google.gson.JsonArray ... though this class does NOT implement List. Alternatively, you could make use of the fact that com.google.gson.JsonArray implements Iterable and write a "for each" loop:
for (JsonElement e: items) {
System.out.println(e);
}
The equivalent code for org.json.JSONArray uses length() instead of size().
In all cases, you should be able to answer your own question by searching for and reading the javadocs for the JSON library that you are using.
UPDATE - Apparently you are using the com.eclipsesource.minimal-json. According to this javadoc, it has a size() method and implements Iterable.

Most Efficient way to create JSON String in java

Currently forming the JSON using the below string in java , will be used in multithreading environment and values will be dynamic after passing the values this JSON will be posted to the 3 rd party web service
"{"
+ " \"test\": {"
+ " \"testCont\": {"
+ " \"size\": {"
+ " \"size\": " + size +","
+ " \"number\": " + number
+ " }"
+ " },"
+ " \"testDate\": {"
+ " \"testAccount\": {"
+ " \"name\": ["
+ testMethod.getName()
+ " ],"
+ " \"school\": {"
+ " \"schoolIdentity\": ["
+ testMethod.schoolIdentity()
+ " ]"
+ " }"
+ " }"
+ " }"
+ " }"
+ "}"
I am aware that using String concatenation will create unnecessary objects in heap
Can some one please tell me the most efficient way to create which will not create additional objects in heap and help to gain performance ?
IF you are converting from Java POJO you can use
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
This will give you the JASON String
Also you can use
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
Refer this https://www.geeksforgeeks.org/convert-java-object-to-json-string-using-jackson-api/

How can I split the data over multiple lines in a JTextArea?

How can I put each line of the host in the message body? I work with a JTextArea.
String host = InetAddress.getLocalHost().getHostName().toString();
texto_recepcion.setText(host + texto_recepcion.getText() + dpRecepcion.getAddress() + " " + mensaje_recibido + "\n");
How it is now:
I resolve my question with append function.
String host = InetAddress.getLocalHost().getHostName().toString();
texto_recepcion.append(host); // ***Use the function append for solve the problem***
texto_recepcion.setText(texto_recepcion.getText() + dpRecepcion.getAddress() + " " + mensaje_recibido + "\n");
Thanks a lot
Why don't you add the newline character "\n" to the beginning of the string?
texto_recepcion.setText("\n" + host + texto_recepcion.getText() + dpRecepcion.getAddress() + " " + mensaje_recibido);

How to pass dynamic value to a JSON String

I have constructed a JSON String this way , but cannot able to pass dynamic values to it
String input = "{\r\n" +
" \"Level\": 0,\r\n" +
" \"Name\": \"String\",\r\n" +
" \"msgName\": \"String\",\r\n" +
" \"ActualMessage\": \"String\",\r\n" +
" \"TimeStamp\": \"/Date(-62135596800000-0000)/\"\r\n" +
"}" ;
String message = "this is value want to pass to the ActualMessage attribute " ;
I need to pass dynamic value to the ActaulMessage atribute
Please tell me how ?
i have tried number of trial and errors but couldn't able to succeed.
Use string concatenation.
String message = "this is value want to pass to the ActualMessage attribute " ;
String input = "{\r\n" +
"\"Level\": 0,\r\n" +
"\"Name\": \"String\",\r\n" +
"\"msgName\": \"String\",\r\n" +
"\"ActualMessage\": \"" + message + "\",\r\n" +
"\"TimeStamp\": \"/Date(-62135596800000-0000)/\"\r\n" +
"}" ;
How about using String.format() for this? for example, to pass a "dynamic value" declare a place holder in the text:
String input = "insert %s in the string"; // here %s is the placeholder
input = String.format(input, "value"); // replace %s with actual value
Now input will contain the string "insert value in the string". In your example, change this line:
" \"msgName\": \"String\",\r\n"
Replace it with this:
" \"msgName\": \"%s\",\r\n"
Now you can perform the substitution:
input = String.format(input, message);
Notice that the first parameter in the format() method has a lot more of options, and that you can pass more than one argument to be replaced. Take a look at the documentation for the Formatter class.
if you want to manipulate Json please consider GSON. your problem can be addressed as follows.
String input = "{\r\n" +
" \"Level\": 0,\r\n" +
" \"Name\": \"String\",\r\n" +
" \"msgName\": \"MessageName\",\r\n" +
" \"ActualMessage\": \"%s\",\r\n" +
" \"TimeStamp\": \"/Date(-62135596800000-0000)/\"\r\n" +
"}" ;
String message = "this is value want to pass to the ActualMessage attribute " ;
String output=String.format(input,message);
//this will replace %s with the content of message variable.

Categories