Get data from JSONObject - java

I have a JSONObject and want to get a String out of it and save it.
SelVehicleJSON (JSONObject):
{
"selVehicle":
{
"_id":"5b38be73257303206ce9b8f9",
"userId":"5b34c591cb6084255857e338"
}
}
I tried
String vehicleId = selVehicleJSON.getString("_id");
but I get the error
W/System.err: org.json.JSONException: No value for _id`.
What am I doing wrong?

The hierarchy seems to be
selVehicle._id
Or set the root before doing
selVehicleJSON.getString("_id");
Edit 1
Try using JsonPath. It makes the life easier and keeps the code clean.
In your case, the code will look like:
public String getValue(JSONObject json, String path) {
return JsonPath.read(json.toString(), path);
}

You should try this :
JSONObject selVehicle = selVehicleJSON.get("selVehicle");
String id = selVehicle.get("_id");

You have two json objects. The outer one is selVehicle and there is a inner json object. So first get the outer json object and use getString on the returned json object.
Try to use this:
import java.io.File;
import static org.apache.commons.io.FileUtils.readFileToString;
import org.json.JSONObject;
File file = new File("Input your json filePath here");
String text = readFileToString(file);
JSONObject jsonObject = new JSONObject(text);
jsonObject = jsonObject.getJSONObject("selVehicle");
System.out.println(jsonObject.getString("_id"));

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

Java read Json array in Json object

I have a String like this:
{"api_authentication":{"api_response":{"token":"XXXXXXXXXXXXXXXXXXXXXXXXX","firstname":"John","disabled":false,"attempts":0,"id":123,"lastname":"Malkovitch","expire":false,"status":0}}}
I can turn this string into an object:
JSONObject jobj = new JSONObject(response);
But I don't find how to get the token value, I tried creating JSONArrays but i get a not found exception.
You can do it like this ;
final JSONObject api_authentication = jobj.getJSONObject("api_authentication");
final JSONObject api_response = api_authentication.getJSONObject("api_response");
System.out.println(api_response.getString("token"));
if JSON any value in curlybrackets { ... } , this is jsonObject . If values are in [ ... ], this is JsonArray. Also you can get which one is object or array, and get it relevant fields from this. So all of json elements are with curly bracket in your problem. Get it as JsonObject.
this might work by the look of what you have posted. The posted code snippet shows that it is a single JSON object and not a JSONArray.
Hence try the following:
JSONObject jobj = new JSONObject(response);
String newtoken = jobj.getJSONObject("api_authentication").getJSONObject("api_response").getString("token"); //declare the variable `newtoken` somhwere before of a desired type
You could try something like:
Object tokenValue = jobj.getJSONObject("api_authentication").getJSONObject("api_response").get("token");
After that you can cast the object to the desired type or use something like getString(.) straightaway.

How to search in Java inside a JSON object for specific key during JSON parsing

I am parsing the following JSON file http://pastebin.com/Mb5E6Ewf using json-simple library in the Java class with name JacksonStreamExample.
In this JSON file I have a JSON object and inside it an array of 6 JSON objects with the following structure:
{"cells": [{object with name START},{object with name END},{object with name ACTIVITY 1},{object with name ACTIVITY 2},{object with name link},{object with name link}]}
I want to search inside these 6 JSON objects for wi_name:START and get wi_displayName of this specific JSON object, but so far in my code I only get all wi_name keys of these 6 JSON objects in an iterator. Can you tell me how to fix my code please?
This is the code of my Java class:
package jsontoxml;
import java.io.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;
public class JacksonStreamExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("text.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray cells = (JSONArray) jsonObject.get("cells");
Iterator<JSONObject> iterator = cells.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().get("wi_name"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
and the output is the following:
START
END
ACTIVITY_1
ACTIVITY_2
null
null
Traversing JSON using org.json API is usually a bit messy since it lacks quite all comfort-features but here you go:
while(iterator.hasNext()){
JSONobject current = iterator.next();
if(current.get("wi_name") != null && current.get("wi_name").equals("START")) {
// maybe do some null- and/or empty-checks here or what ever you want with the data
System.out.println(current.get("wi_displayName"));
};
}
Hope this helps!
I solved my problem by changing my code this way:
while(iterator.hasNext()){
JSONObject jsonObject2 = (JSONObject) iterator.next();
if(jsonObject2.get("wi_name").equals("START")){
System.out.println(jsonObject2.get("wi_displayName"));
}
}

Java - Retrieving nested JSON array key values

I've got a JSON response that looks like this:
USER:[{
"id":"145454",
"name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true,
"caregiverName":"Jones"
}]
I'm trying to create a java method so I can access the key value pairs of the nested JSONArray. For example I don't want the entire JSON array I just want to retrieve the doctor name from the patientInfo JSON array. Any ideas how I would do this in Java I'm completely stuck here.
This is sudo code but I imagine it would be something like:
String doctorInfo() {
JSONObject obj = new JSONObject(user)
JSONArray arr = obj.getJSONArray("patientInfo")
String doctor = arr.getValue("doctor")
}
And I'd like to be able to access it on the front end by doing
doctorInfo().doctor
Code samples are greatly appreciated.
The code will be like this:
String doctorInfo(String jsonString) {
JSONObject obj = new JSONObject(jsonString)
JSONArray arr = obj.getJSONArray("patientInfo")
JSONObject patientJSONObject = arr.getJSONObject(0);
String doctor = patientJSONObject.getString("doctor");
return doctor;
}
The above code sample assumes you are passing the below string as the parameter.
{ "id":"145454", "name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true, "caregiverName":"Jones" }

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

Categories