how to print nested json-object without escapes and quotation marks - java

i have a json-object named jsonObject
{
"action":"Read",
"infos":[
{
"value":0.0350661,
"key":"first"
}
]
}
i wanna to print the json-object to with the following form
{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}
if i use jsonObject.toString() method i will get
{"action":"Read","infos":"[{\"value\":0.0350661,\"key\":\"first\"}]"}
if i use StringEscapeUtils.unescapeJava(jsonObject.toString()) method i will get
{"action":"Read","infos":"[{"value":0.0350661,"key":"first"}]"}
if i use jackson mapper with the following code
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
String jsonString = mapper.writeValueAsString(getDebugInfo())
i will get jsonString as
{"nameValuePairs":{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}}
is there any solution to get the desired output json-string?

JSON Structure
You have that as an object, that is why quotes are not present there.
In your example, an array object is present, at the Json structure.
Code/Java
While printing at Console, the json body's every Key & Value toString() are referred .
That is why the Double Quotes present, as Strings are getting used!

Here I have tried the below code using GSON library, and it is printing me the correct json as shown above.
public static void main ( String [] args ) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", "Read");
JsonArray jsonArr = new JsonArray();
JsonObject jsonObject2 = new JsonObject();
jsonObject2.addProperty("value", 0.0350661);
jsonObject2.addProperty("key", "first");
jsonArr.add(jsonObject2);
jsonObject.add("infos", jsonArr);
String jsonString = jsonObject.toString();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement json = gson.fromJson(jsonString,JsonElement.class);
String jsonInString = gson.toJson(json);
System.out.println(jsonInString);
}
OUTPUT:
{
"action": "Read",
"infos": [
{
"value": 0.0350661,
"key": "first"
}
]
}
Even if I am forming the jsonObject using org.json, and simple printing it using System.out.println(jsonObject.toString()); on console, m getting the result like this.
{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}
So here, not sure how you have formed your jsonObject.

Related

How to remove extra escaping quote characters of JsonObject created through Javax

I use javax to create JsonObject and JsonArray from my List<String> and I have a list of Json objects that i want to put in a JsonObject through a JsonArray
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String Obj : listOfJsonDfObjects)
jsonArray.add(summaryObj); //{"a":"b"},{"c":"d"}
// this line introduces extra escaping quotes like this {"\"a\"":"\"b\""},{"\"c\"":"\"d\""}
javax.json.JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
How to avoid these extra quotes escaping characters?
Thanks
You say you have a list of JSON objects, but you really have a list of JSON-formatted strings. To add them to a JsonArray, you need to parse each one into the JSON object model:
public class JsonTest {
public static void main(String[] args) {
List<String> listOfJsonDfObjects = List.of(
"{\"a\":\"b\"}",
"{\"c\":\"d\"}"
);
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String summaryObj : listOfJsonDfObjects) {
JsonReader parser = Json.createReader(new StringReader(summaryObj));
jsonArray.add(parser.readObject());
}
JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
System.out.println(data); // {"data":[{"a":"b"},{"c":"d"}]}
}
}
Using Gson
Gson gson = new Gson();
String json = gson.toJson(listOfJsonDfObjects);
//check json
System.out.println(json);
json = json.replaceAll("\\\\", "");
json = json.replaceAll("\"\\{", "{");
json = json.replaceAll("\\}\"", "}");
//valid json now
System.out.println(json);
A more secure way (to avoid altering original data)
//concatenate objects in list with comma
String json = String.join(",", listOfJsonDfObjects);
//convert to pseudo array
json = "[" + json + "]";
//convert pseudo json array to pseudo json object
json = "{\"data\":" + json + "}";
//cast to json object
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject);

JSON Input for POST request to call REST API

How do i convert a model Person to match the input?
Person p = new Person(name, age, amountInBank);
(name in String, age in int and amountInBank in double)
I want my JSON Input to be as follow:
{
"ID": "H123",
"list" : [
{
"name" : "ally",
"age": 18,
"amountInBank": 200.55
}
]
}
Currently my code to call REST API is:
JSONObject jsonInput= new JSONObject();
jsonInput.put("ID", "H123");
//put in list input in JSON -> HELP NEEDED
Resource resource = client.resource(URL HERE);
resource.contentType(MediaType.APPLICATION_JSON);
resource.accept(MediaType.APPLICATION_JSON);
ClientResponse cliResponse = resource.post(jsonInput);
Tried many ways but couldn't achieve the expected input for list in JSON format. Please help
Method 1:
ArrayList<Map<String, Object>> list = new ArrayList<>();
list.add(p);
jsonInput.put("list" , list);
Method 2:
JSONArray jsonArr = new JSONArray();
jsonArr.add(p);
jsonInput.put("list", jsonArr);
Method 3:
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "ally");
map.put("age", 18);
map.put("amountInBank" : 255.55);
jsonInput.put("list", map);
Safest bet is to use a well known library for the marshalling, such as Jackson. It is able to convert your object to JSON format with the following:
ObjectMapper mapper = new ObjectMapper(); //from Jackson library
Person p = new Person(name, age, amountInBank); //your POJO
String jsonString = mapper.writeValueAsString(p); //convert
Source: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
There are also other alternatives, this is just a personal preference as Jackson is very widely used and well documented.
If you're trying to get a list of array JSON objects then just substitute the Person object with List<Person> and try to marshall that.
Try the code below
val listJsonArry = JsonArray()
var jsonObject = JsonObject()
jsonObject.add("name", "ally")
jsonObject.add("age", "18")
jsonObject.add("amountInBank", "200.55")
listJsonArry.add(jsonObject)
PostData
var postjsonObject = JsonObject()
postjsonObject.add("ID", "H123")
postjsonObject.add("list", listJsonArry)
First you have to create JSONObject and put ID, H123.
Then you have to create Another JSONObject wich will accept a person details.
pass another JSONObject to JSONArray and path JSONArray to JSONObjct. check the code
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject(); // first json object
jsonObject.put("ID", "H123"); put ids.
JSONArray jsonArray = new JSONArray(); // prepear json array
Person person = new Person("Ally", 18, 200.55); // create person object and populate it with data
// JSONObject jsonObject = new JSONObject(person); you can pass your person directly to JSONObject constructor and it will deparse it base on your getter methods in person class.
JSONObject jsonObject1 = new JSONObject(); // then pass person data to Json object
jsonObject1.put("name", person.getName());
jsonObject1.put("age", person.getAge());
jsonObject1.put("amountInBank", person.getAmountInBank());
jsonArray.put(jsonObject1); // pass json object to json array
jsonObject.put("list", jsonArray); // and pass json array to json object
System.out.println();
try (FileWriter file = new FileWriter("person.json")) {
file.write(jsonObject.toString(5));
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
above code will produce output
{
"ID": "H123",
"list": [{
"name": "Ally",
"amountInBank": 200.55,
"age": 18
}]
}
if you need to do that from database, more like there will be a lot of persons. put person object and json object in some kind of loop and populate it as long as you want. then pass it to json array and json array to jsonobject to have many records.

How to get deeply nested JSON object in Java

I have a JSON string where i want to get the value of one field which is nested in multiple objects. How can I get that field in a nice and performant way? Here's the code I tried so far. It's working, but it's quite lengthy code. I'm looking for a better solution.
Json Response
{
"status":"success",
"response":{
"setId":1,
"response":{
"match":{
"matches":{
"matchesSchema":{
"rules":[
{
"ruleId":"Abs"
}
]
}
}
}
}
}
lengthy code:
JsonParser jp=new JsonParser();
Object obj = jp.parse(JSONString);
JSONObject jsonObject =(JSONObject) (obj);
JSONObject get1 = jsonObject.getJSONObject("response");
JSONObject get2 = get1 .getJSONObject("response");
JSONObject get3 = get2 .getJSONObject("match");
JSONObject get4 = get3 .getJSONObject("matches");
JSONObject get5 = get4 .getJSONObject("matchesSchema");
JSONObject get6 = get5 .getJSONObject("rules");
JSONArray result = get6 .getJSONArray("rules");
JSONObject result1 = result.getJSONObject(0);
String lat = result1 .getString("rule");
The result is
ruleId = Abs
is there a good alternative for fetching the ruleId from the nested json object (something like response.response.match.matches.matchesSchema.rules.ruleId)
You can use Jackson's JsonNode with JsonPath to get ruleId as follows:
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObj = mapper.readTree(JSONString);
String lat = jsonObj.at("/response/response/match/matches/matchesSchema/rules/0/ruleId").asText()
It's also null-safe and returns a MissingNode object on a null node that returns an empty string when you do a .asText()
It's super easy with JsonPath.
String ruleId = JsonPath.read(jsonString, "$.response.response.match.matches.matchesSchema.rules[0].ruleId");
Or if you read the path multiple times, it's better to pre-compile JsonPath expression
JsonPath ruleIdPath = JsonPath.compile("$.response.response.match.matches.matchesSchema.rules[0].ruleId");
String ruleId = ruleIdPath.read(json);

Removing backslash from JSON format while programmatically constructing a JSON array

I want to parse the JSON data by removing the backslash from the JSON format.
I have tried removing the backslash from the JSON format by the following code but nothing worked out
JSONArray packsJSON = new JSONArray();
JsonObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JsonObject();
innerObject.addProperty("pack_id",packageList.getSubs_id());
innerObject.addProperty("pack_dsc", packageList.getSubs_desc());
innerObject.addProperty("pack_tax_amt", packageList.getTax_amnt());
innerObject.addProperty("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}
output of INNEROBJECT:
{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}
The output of PACKJSON:
[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}",
"{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"
]
[
"{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}",
"{"pack_id":"2232","pack_dsc":"Bangara(280)","pack_tax_amt":"0","pack_grand_total":"280"}"
]
Your JSONArray is of org.json package and JsonObject is of com.google.gson package
so your innerObject's type should be org.json.JSONObject
JSONArray packsJSON = new JSONArray();
JSONObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JSONObject();
innerObject.put("pack_id",packageList.getSubs_id());
innerObject.put("pack_dsc", packageList.getSubs_desc());
innerObject.put("pack_tax_amt", packageList.getTax_amnt());
innerObject.put("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}
Please check below answer.
String jsonString = "[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}","{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"]"
String outputString = jsonString.replaceAll("\\\\", "");
Log.e("Clear String :", outputString);
OUTPUT

Is JSON same with GSON?

I have tried to run following code
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("sEcho", echo);
jsonResponse.put("iTotalRecords", iTotalRecords);
jsonResponse.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse.put("aaData", json);
jsonResponse.toString();
JSONArray data = new JSONArray();
for (Object obj : result) {
JSONArray row = new JSONArray();
User user = (User) obj;
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
JSONObject jsonResponse2 = new JSONObject();
jsonResponse2.put("sEcho", echo);
jsonResponse2.put("iTotalRecords", iTotalRecords);
jsonResponse2.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse2.put("aaData", data);
jsonResponse2.toString();
The result from toString function for both jsonResponse are as follows:
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":"[{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"password\":\"asda\",\"userName\":\"abiieez\"}]","sEcho":"1"}
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":[[1,"abiieez",true]],"sEcho":"1"}
I would like to eliminate the " symbol before [ and after ] from the first json response just like the second one (I noticed that the " is added after the array being put to the jsonResponse object). How can I accomplish this ?
Since you first convert your "result" to a String, and then add it to aaData, it will end up quoted, like a String should. If all you'd like to do is to remove the quotes, you could do something like this in line 2:
String json = "##" + gson.toJson(result) + "##";
and this in line 8:
jsonResponse.toString().replace("\"##", "").replace("##\"","");
(of course you need to choose the "quote marker" ## such that it will never appear as actual string content in your data anywhere else)
But the cleaner solution (although probably slower) would likely be to convert your String to an actual JSONObject by changing line 2 to:
JSONObject json = new JSONObject(gson.toJson(result));

Categories

Resources