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

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);

Related

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

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.

Java: Extract json values as individuals

I have this json in java:
jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.
Is there an easy way to extract all the values as individuals like jsonObj [1]?
You may Use Gson parsing library as below :
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
or simply use:
example
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
for Array use :
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
You should use a library to deserialize your JSON in a Java Object.
Libraries like GSON, Genson or Jackson.
Once you transform the json in a object, it will have a property called "ps" that will be an array (or a List)

how to parse simple json string array to object in java

I have a json array as a string in the following format:
[ "Ford", "BMW", "Fiat" ]
which is a legal json string. How am I able to use Gson to save into an object?
When I am trying to use getAsJsonArray(), but I get an error:
java.lang.IllegalStateException: This is not a JSON Array.
Use Gson to parse your Json array.
String input = "[ 'Ford', 'BMW', 'Fiat' ]";
Gson gson = new Gson();
String[] output = gson.fromJson(input, String[].class);
for(String s : output){
System.out.println(s);
}
Output
Ford
BMW
Fiat
You can use this to get value into arraylist using getAsJsonArray() Method
String jsonStr = "['Ford', 'BMW', 'Fiat' ]";
JsonArray root = new JsonParser().parse(jsonStr).getAsJsonArray();
Gson gson = new Gson();
ArrayList<String> staff = new ArrayList<>() ;
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(root, listType);
System.out.println(yourList );

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

Parsing String to JsonObject using GSON gives IllegalStateException: This is not a JSON Object

I have the following code:
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonObject json = parser.parse(gson.toJson(roomList)).getAsJsonObject();
System.out.println("json: " + json);
It gives me the following output:
gson.toJson: [{"id":"8a3d16bb328c9ba201328c9ba5db0000","roomID":9411,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328b9f3a01328b9f3bb80000","roomID":1309,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328ba09101328ba09edd0000","roomID":1304,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bb8af640000","roomID":4383,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd271fe0001","roomID":5000,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd2e0e30002","roomID":2485,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3087b0003","roomID":6175,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd35a840004","roomID":3750,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd366250005","roomID":370,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3807d0006","roomID":9477,"numberOfUsers":4,"roomType":"BigTwo"}]
json2: {"b":"c"}
java.lang.IllegalStateException: This is not a JSON Object.
Can someone please help me parse my Json string to JsonObject? I have checked in http://jsonlint.com/ that my json is valid though.
It's because due to the JSON structure..
I have to put it into a JSONObject first, like so
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(ServerConstants.JSONoutput, gson.toJson(roomList));
Then I would deserialize like
List<RoomData> roomList = gson.fromJson(jsonObj.get(CardGameConstants.JSONoutput).toString(), listType);
for (RoomData roomData : roomList) {
System.out.println(roomData.getRoomID());
}
This should give you some basic idea.
ArrayList<String> roomTypes = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for(int i =0; i<jsonArray.length(); i++){
roomTypes.add(jsonArray.getJSONObject(i).getString("roomType"));
}
The problem with the code is that roomList is not a JsonObject as evident in the printed output. It's actually a JsonArray.
To fix the code, call .getAsJsonArray() (instead of .getAsJsonObject())
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonArray json = parser.parse(gson.toJson(roomList)).getAsJsonArray();
System.out.println("json: " + json);

Categories

Resources