error in parsing JSON in java - 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")

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

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

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

How to get the values from keys in nested objects using only json-simple

I want to get only a specific value out of all the nested objects. In the application I just need the msg 3 which is inside another object messages.
I have tried it using JSONObject but it is not working for nested object. However It is working with just a single object means root object .
INPUT - {"name":"lola","messages":{"msg 1":"msg 2","msg 3":"msg 4"},"age":22}
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
Object name = json.get("messages");
System.out.println(name);
JSONObject messageObject = (JSONObject) json.get("messages");
System.out.println(employeeObject);
//Get employee first name
String msg= (String) messageObject.get("msg3");
System.out.println(msg);
The Output:
{"msg 3":"msg 4","msg 1":"msg 2"}
{"msg 3":"msg 4","msg 1":"msg 2"}
null
The last nested object is not fetching in any way. Another thing is that the normal print of the string as a JSONObject gets changed. like the msg3 came before msg1.
In place of null - msg4 should be there.
Thanks in advance.
You are missing a space between "msg" and "3". By the way - you can do this easier, as such.
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
System.out.println(json.get("message").get("msg 3"));

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.

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.

Categories