Below is the sample code:
import org.json.JSONArray
import org.json.JSONObject
JSONObject jsonObject = new JSONObject("{\"Status\":200,\"Description\":\"Success\",\"Result\":\"{\\\"Id\\\":\\\"ABCD123\\\",\\\"clientId\\\":\\\"0c34c71c\\\",\\\"status\\\":\\\"Finished\\\",\\\"message\\\":\\\"Done\\\",\\\"type\\\":\\\"registration\\\"}\"}")
/*
here I want to do something like:
JSONObject innerJsonObj = (JSONObject) jsonObject.get("Result");
String id = innerJsonObj.get("clientId");
*/
On executing JSONObject innerJsonObj = (JSONObject) jsonObject.get("Result"); - it gives:
Exception in thread "main" java.lang.ClassCastException: Cannot cast object '{"Id":"ABCD123","clientId":"0c34c71c","status":"Finished","message":"Done","type":"registration"}' with class 'java.lang.String' to class 'org.json.JSONObject'
So what modification I need to do for fetching the values present in nested JsonObject( i.e Result)
Your JSON:
{
"Status": 200,
"Description": "Success",
"Result": "{\"Id\":\"ABCD123\",\"clientId\":\"0c34c71c\",\"status\":\"Finished\",\"message\":\"Done\",\"type\":\"registration\"}"
}
As you can see, the value of Result is a string, not a JSON object.
So you'd need to create a new JSONObject from that string:
JSONObject jsonObject = new JSONObject("{\"Status\":200,\"Description\":\"Success\",\"Result\":\"{\\\"Id\\\":\\\"ABCD123\\\",\\\"clientId\\\":\\\"0c34c71c\\\",\\\"status\\\":\\\"Finished\\\",\\\"message\\\":\\\"Done\\\",\\\"type\\\":\\\"registration\\\"}\"}");
JSONObject innerJsonObj = new JSONObject(jsonObject.getString("Result"));
String id = innerJsonObj.getString("clientId");
Related
I'm trying to read a JSONObject from within another JSONObject. The first output works, the second, i.e. the JSONObject within, does not. Here I get the following error
org.json.JSONException: JSONObject["Values"] not found.
This is the output of the first object / array
ergebnis: {"Description":"","Objects":[{"RefStr":"76-1044-0","ClassName":"Application","Values":{"providerorg-refstr":"262-462-0",...}]}
This is how I try to get the data:
JSONObject jsonObject = new JSONObject(ergebnis);
System.out.println(jsonObject);
JSONObject inside = jsonObject.getJSONObject("Values");
System.out.println(inside);
Values object is present in Objects. This objects is an array. You can try like below,
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject);
JSONObject jsonObject1= jsonObject.getJSONObject("ergebnis");
System.out.println(jsonObject1);
JSONArray objects = jsonObject1.getJSONArray("Objects");
System.out.println(objects);
JSONObject inside = objects.getJSONObject(0).getJSONObject("Values");
System.out.println(inside);
I tried to build the nested array for the following json blob using jsonobject and jsonarray. For some reason, the object is failing. Any thoughts - please, how best we can put this format.
{
"reporter_desc": "pot",
"timestamp": "1487830751",
"incidents": [
{
"src_ip": 822382162,
"exploit": "scan",
"incident_type": 3,
"occurred": "1487830751",
"description": "pot scan"
}
Here is the JSONObject and JSONArray :
JSONObject object = new JSONObject();
object.put("reporter_desc", "mtpot");
object.put("timestamp", "1487830751");
JSONArray array = new JSONArray();
JSONObject arrayElement = new JSONObject();
arrayElement.put("src_ip", 822382162);
arrayElement.put("exploit", "scan");
arrayElement.put("incident_type", 3);
arrayElement.put("occurred", "1487830751");
arrayElement.put("description", "pot vulnerability scan");
array.put("incidents");
object.put("incidents", array);
i am trying to phrase the below json response and the get the "message" and "WORKORDERID" data in java
{
"operation": {
"result": {
"message": " successfully.",
"status": "Success"
},
"Details": {
"SUBJECT": "qqq",
"WORKORDERID": "800841"
}
}
}
Below is my code
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject jsonobject = (JSONObject) inputs.get("operation");
String s = jsonobject.getString("message");
system.out.println("s");
Your objects are nested 2 times, therefore you should do:
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject operation= (JSONObject) inputs.get("operation");
JSONObject result= (JSONObject) operation.get("result");
JSONObject details= (JSONObject) operation.get("Details");
String message = result.getString("message");
String workerId = details.getString("WORKORDERID");
JSONObject is somethink like Map-Wrapper, so you can think, that your JSON data-structure is Map<Map<Map<String, Object>, Object>, Object>. So, firstly you need to access to datas by first key (operation), secondly (result) and after that, you can access to desired field (message).
Note, that value of Map is Object, so you will need to cast your type to JSONObject.
sometimes JSONObject class is not found in java. so you will need to add jar
try{
// build the json object as follows
JSONObject jo = new JSONObject(jsonString);
// get operation as json object
JSONObject operation= (JSONObject) jo.get("operation");
// get result as json object
JSONObject result= (JSONObject) jo.get("result");
JSONObject details= (JSONObject) jo.get("Details");
// get string from the json object
String message = jo.getString("message");
String workerId = jo.getString("WORKORDERID");
}catch(JSONException e){
System.out.println(e.getMessage());
}
I've a JSON Array:
JSON_STRING = [{"name": "adminparking1", "id": 1},{"name": "adminparking2", "id": 2}]
And I Want to parse it to a JSON-simple Array and work with json Objects that it provides from it examples I do it this way:
JSONParser jsonParser = new JSONParser();
Object res_obj = jsonParser.parse(JSON_STRING);
JSONArray json = (JSONArray) res_obj; //(HERE Error Occurs)
It gives me this error:
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
how can i get rid of this error?
This code works just fine, if JSON string is valid
public static void main() throws ParseException {
String JSON_STRING = "[{\"name\": \"adminparking1\", \"id\": 1},{\"name\": \"adminparking2\", \"id\": 2}]";
JSONParser jsonParser = new JSONParser();
Object res_obj = jsonParser.parse(JSON_STRING);
JSONArray json = (JSONArray) res_obj; // no Error
System.out.println(json.get(1));
}
prints
{"name":"adminparking2","id":2}
Have you tried this:
JSONArray arr = new JSONArray(JSON_STRING);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
}
I am using the following library to parse an object:
{"name": "web", "services": []}
And the following code
import com.json.parsers.JSONParser;
JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);
when the array services is empty, it displays the following error
#Key-Heirarchy::root/services[0]/ #Key:: Value is expected but found empty...#Position::29
if the array services has an element everything works fine
{"name": "web", "services": ["one"]}
How can I fix this?
Thanks
Try using org.json.simple.parser.JSONParser
Something like this:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);
Now to access the fields, you can do this:
JSONObject name = jsonObject.get("name"); //gives you 'web'
And services is a JSONArray, so fetch it in JSONArray. Like this:
JSONArray services = jsonObject.get("services");
Now, you can iterate through this services JSONArray as well.
Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
while (iterator.hasNext()) {
// do something. Fetch fields in services array.
}
Hope this would solve your problem.
Why do you need parser?
try this:-
String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());
I solve the problen with https://github.com/ralfstx/minimal-json
Reading JSON
Read a JSON object or array from a Reader or a String:
JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );
Access the contents of a JSON object:
String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...
Access the contents of a JSON array:
String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...