Why am I getting a JSON exception while calling .getJSONObject()? - java

I want to generate JSON with URI within the JSON response but I'm getting JSON exception when I tried to get a value of the key. Here fragmentdataservice is to get JSON data and it working fine and I'm working on API creation with content fragments.
String requestURI = req.getRequestURI();
String contentFragmentName = requestURI.substring(requestURI.indexOf('.') +
1, requestURI.lastIndexOf('.'));
resp.setContentType("application/json");
response = fragmentDataService.getContentFragment(contentFragmentName);
String contentReference = response.getJSONObject("poolingInfo").toString();
JSONObject contentData = fragmentDataService.getContentFragment(contentReference);
response.put("poolingInfo", contentData);

JSON exception will be thrown if you're trying to read a String data or a JSONArray data as a JSONObject using getJSONObject() method.
If you're not sure what's the type of object that's being returned then first use:
Object temp = response.get("poolingInfo");
if(null != temp && temp instanceof JSONObject) {
String contentReference = ((JSONObject) temp).toString();
}

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

error in parsing JSON in java

I have a response from API that generates authorization token with some other attributes, I'm trying to extract the value of the token from the response which looks like below
{"access_token":"tokenvalue","scope":"somevalue","token_type":"Bearer","expires_in":value}
i tried JSON parse like below:
Myclass response = template.postForObject(url, requestEntity, Myclas.class);
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(response);
String product = (String) jsonObject.get("access_token");
token = response;
}
Recieved error:
parse( ) 
in JSONParser cannot be applied
to
(java.lang.String)
With the line:
String product = (String) jsonObject.get("access_token");
You are trying to get a property called "access_token".
However if you look at your json you will see that there is no property called "access_token".
Perhaps you meant:
String product = (String) jsonObject.get("token");
Like said by Neng Liu before me, this JSON could be incorrect:
{"token":"tokenvalue","scope":"somevalue","token_type":"Bearer","expires_in": value }
Another thing is that JSONObject can receive the JSON format in its constructor JSONObject obj = new JSONObject(response) in your case and then use obj.get("your filed")

JSON-simple get JSONObject using method

I have been working on a project that requires JSON for getting data from a large json file, but I ran into a problem when trying to get a json string using a method.
the method for getting the ID works I have tested this multiple times. When I enter int he ID as a string it also works prefectly but when I use the method to get the jsonString it stops working and gives a nullpoiterexeption
public static int getLvlMin(ItemStack is) throws ParseException {
String id = getID(is);
system.out.println(id);
JSONParser parser = new JSONParser();
Object obj = parser.parse(Main.weapons);
JSONObject jsonObj = (JSONObject) obj;
system.out.printlnjsonObj.toJSONString());
JSONObject weapon = (JSONObject) jsonObj.get(String.valueOf(getID(is)));
system.out.println(weapon.toJSONString());
return 1;
}
This is the json string I am trying to get info {"W1121000-00002":{"clnt":1023,"srvr":870}} and I am trying to get the clnt value out of that string.

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

JSON Object is null while parsing

The format of my json object is:
String jsonObjRecv = {
"response":{
"respobj":{
"id":<int>,
"number":<string>,
"validated":<boolean>
}
},
"status":"ok",
"errors":null
}
It works when code is:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
String getString= jsonObjCont.toString(2);
In this case getString != null and I can receive data, but when I try to get nested data of JSON object as like:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
JSONObject regNumber = jsonObjCont.getJSONObject("respobj");
String number= regNumber.getString("number");
it dont work.
I tried to use GSON library, but it works when:
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
String result = jelement.toString();
return result;
and don't work :
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("respobj");
String result = jobject.get("number").toString();
return result;
Where is my mistake?
The problem is you're not accessing your JSON object correctly - it's an object that contains a response object which contains a respobj object.
Gson example follows. Note the comment in the code - you need to get the response object then get the respobj from it.
public static void main( String[] args )
{
String jsonObjRecv = "{\"response\":{\"respobj\":{\"id\":1,\"number\":\"22\",\"validated\":true}},\"status\":\"ok\",\"errors\":null}";
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
// Here is where you're making an error. You need to get the outer
// 'response' object first, then get 'respobj' from that.
jobject = jobject.getAsJsonObject("response").getAsJsonObject("respobj");
String result = jobject.get("number").getAsString();
System.out.println(result);
}
Output:
22
Edit to add: Note I used getAsString() vs. toString() - if you use the latter you get the raw JSON which will incluse the quotes around the value (e.g. the output would be "22")

Categories