how to extract json body as string using java - java

I have a JSON response and i am extracting the body using getbody() command and storing the responses in list. because i am passing multiple JSON at a time so each response i am storing in list as string value. How can i extract that JSON using JAVA?
response = request.post(route.payment());
body = response.getBody();
listofBody.add(body.asString());
above code is where i get the response and store that into list. before converting to JSON i can do response.jsonPath().getList("company"); to get the values

To extract the element from JSON string you can use Google's Gson Library
Example:
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass().getSimpleName());
}

Related

Org json parsing keep getting error - is not a JSONObject

Im trying to parse id from following string json:
postResponse :{"success":true,"response_json":"{\"status\":200,\"message\":\"Success\",\"data\":{\"id\":\"f71233gg12\"}}"}
my code looks like below:
System.out.println("postResponse :"+postResponse);
JSONObject responseJson = new JSONObject(postResponse);
JSONObject jsonObjectA = responseJson.getJSONObject("response_json");
JSONObject jsonObjectB = jsonObjectA.getJSONObject("data");
String the_pdf_id = jsonObjectB.get("id").toString();
i keep getting the error:
org.json.JSONException: JSONObject["response_json"] is not a JSONObject.
what could be the reason? any solution for that?
As you can see on your data, the content at key response_json is not a an object, but only a string, another JSON-encoded string
// response_json value is a string
{"success":true,"response_json":"{\"status\":200,\"message\":\"Success\",\"data\":{\"id\":\"f71233gg12\"}}"}
// response_json value is an object
{"success":true,"response_json": {"status":200,"message":"Success","data":{"id":"f71233gg12"}}}
You need a second parse level
JSONObject jsonObjectA = new JSONObject(responseJson.getJSONString("response_json"));

Using Java, how to add some node to an existing json at the start of array?

The below code inserts the "myvalue" field to the existing JSON but after the "id" key-value pair, I want to insert a value in this JSON but before the "id" field.
String originalJson="{"checkouts":[{"line_items":[{"id":"343f1f49d0ba7752b5ba84e0184384f4"}]}]}";
String modifiedJson= JsonPath.parse(originalJson)
.add("$.checkouts[0].line_items","myValue")
.jsonString();
The current output of the above code is :
{"checkouts":[{"line_items":[{"id":"343f1f49d0ba7752b5ba84e0184384f4"},"myValue"]}]}
But I want an output like this :
{"checkouts":[{"line_items":["myValue",{"id":"343f1f49d0ba7752b5ba84e0184384f4"}]}]}
You can do this:
String originalJson="{\"checkouts\":[{\"line_items\":[{\"id\":\"343f1f49d0ba7752b5ba84e0184384f4\"}]}]}";
DocumentContext json = JsonPath.parse(originalJson);
JSONArray array = json.read("$.checkouts[0].line_items");
array.add(0, "myValue");
String modifiedJson= json
.set("$.checkouts[0].line_items",array)
.jsonString();

Parsing String to JsonObject

I'm getting a list of values from a query with MongoDB I'm using MongoRepository and the method findAll, the answer I'm getting is a List of Informacion
public Informacion[] getAll() {
List<Informacion> info = repoInfo.findAll();
String json =new Gson().toJson(info);
Informacion[] array = info.toArray(new Informacion[info.size()]);
return array;
}
the list I'm getting I parse into JSON, but I can't convert it into a JSONObject to work properly with all the values inside, this is the JSON string :
Informacion{ preferencias=[Preferencias(nombrePref=Rock),
Preferencias(nombrePref=Tatuajes)], numTelefono='0984623854',
usuario='#Bryan810', redes=[RedesSociales(nombreRedSocial=Twitter)],
fechaRecarga=Fri Dec 21 11:30:59 COT 2018}
working with this as a String is really hard because values like Preferencias has many values but if I can transform the String to JSONObject I think I can't handle it better.
So my question is how can I transform "JSON" String to a JSONObject?

How to modify the JSON data and return the updated JSON data

We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}
For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")
We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
String result = "";
for(String key : keys)
{
if (jsonObject.get(key) instanceof JsonObject)
{
jsonObject = (JsonObject)jsonObject.get(key);
}
else if(jsonObject.get(key) instanceof JsonArray)
{
JsonArray jsonArray = (JsonArray)jsonObject.get(key);
result = jsonArray.toString();
}
else
{
result = jsonObject.get(key).toString();
}
}
result = result.replace(result, updateText);
return result;
}
The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for(String key : keys)
{
if (jsonObject.get(key).isJsonObject())
{
jsonObject = (JsonObject)jsonObject.get(key);
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
.set("use the path to go for value", "new value").json();
json = updatedJson.toString();

how to get the name of json object from my json array

I am trying to get the name of my json key from my jsonarray but not able to take in java.
[{"ParamName":"param1","DefaultValue":"","Hidden":"Hidden","LinkedParameter":"city"}]
I just want to take name of key like i only want to take "ParamName" and need to check
if (ParamName == "ParamName") {
Then do this.
}
You can convert this to JSON object.
JSONArray json = (JSONArray)new JSONParser().parse("[{\"ParamName\":\"param1\",
\"DefaultValue\":\"\",\"Hidden\":\"Hidden\",\"LinkedParameter\":\"city\"}]");
JSONObject obj= (JSONObject) json.get(0);
if("ParamName".equals(obj.get("ParamName"))){
}

Categories