JSON traversing in java - java

i want traverse and get particular value from the json i am giving below .
json={"resultMessage":["{\"retain24ErrorMessage\":\"No result data found!\"}","TemplateId or instanceId is empty!"],"isSuccessful":true}
The value i want to get is retain24ErrorMessage value. I have tried the following.
Object JSONArrayCheck = json.get("resultMessage");
String errMsg1 = (String)json.getJSONArray("resultMessage").get(0);
Gson gson = new Gson();
// JsonElement jsonObject = gson.toJsonTree(json.getJSONArray("resultMessage").get(0));
JsonElement jelement = new JsonParser().parse(gson.toJson(errMsg1));
JsonObject jobject = jelement.getAsJsonObject();
But is not working and following error comes
12-11 17:17:16.300: W/System.err(1780): java.lang.IllegalStateException: Not a JSON Object: "{\"retain24ErrorMessage\":\"No result data found!\"}"
. Can you give me demo for retrieving the same retain24ErrorMessage ?

gson.toJson(errMsg1) expects an Object but the passed errMsg1 is a string.
Don't you need to do something like this instead?
JsonElement jelement = new JsonParser().parse(errMsg1);

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

GSON - remove JSON data from JSON object

I'm looking to remove part of a JSON object, at the moment I only seem to be able to return the whole object.
JSON format:
{"blobJson":"{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}","deviceMfg":2,"eventCode":101,"sensorClass":1,"sensorUUID":"111122","timeStamp":1.53907307310099994E18,"uID":"111122_1_2"}
I'm looking to remove the [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] part of the JSON.
At the moment I'm using the following code:
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
System.out.println(rootobj);
This is outputting the following JSON:
{"blobJson":"","deviceMfg":-1,"eventCode":-1,"sensorClass":-1,"sensorUUID":"","timeStamp":0.0,"uID":"_-1_-1"}
If you want to remove the framedata key and value from the string. You can use the org.json.JSONObject as shown below:
JSONObject jo1 = new JSONObject("{\"blobJson\":{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},\"deviceMfg\":2,\"eventCode\":101,\"sensorClass\":1,\"sensorUUID\":\"111122\",\"timeStamp\":1.53907307310099994E18,\"uID\":\"111122_1_2\"}");
jo1.getJSONObject("blobJson").remove("frameData");
If you want to retain the key framedata but want only the value to be replace with [] then do the following:
JSONObject jo1 = new JSONObject("{\"blobJson\":{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},\"deviceMfg\":2,\"eventCode\":101,\"sensorClass\":1,\"sensorUUID\":\"111122\",\"timeStamp\":1.53907307310099994E18,\"uID\":\"111122_1_2\"}");
jo1.getJSONObject("blobJson").put("frameData", "[]");
You can use ObjectMapper from com.fasterxml.jackson.databind but then you require the corresponding class also with all the member variables corresponding to the json keys. In the above approach you can directly manipulate the Json String.
String stringifyRequest="{"blobJson":"{\"sensorID\":\"111122\",\"width\":32,\"height\":31,\"frameData\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}","deviceMfg":2,"eventCode":101,"sensorClass":1,"sensorUUID":"111122","timeStamp":1.53907307310099994E18,"uID":"111122_1_2"}";
final ObjectMapper mapper = new ObjectMapper();
"Yourpojoclass" investmentResponse = mapper.readValue(stringifyRequest, "Yourpojoclass".class);
here "Yourpojoclass" would be your class which consists string field parameter:
Now set your frameData value null and make your pojo class #JsonInclude(value=Include.NON_NULL)
and then convert it again in 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.

Java JSON parse array

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(), ...

Insert node in a JSON String

Using Google Gson library how can I inject a element in the root node of a JSON string?
With JSON.Simple it very easy:
String json = ...
JSONObject jsonObj = (JSONObject) JSONValue.parse(json);
jsonObj.put("hey", "yow!");
json = jsonObj.toJSONString(); // Now we have injected a node element
I've been figuring out how can do this with Gson. You might ask why I need Gson when I can do this with JSON.Simple library; the answer is that, there's a handy object serialization/deserialization function that the library have.
The code is strikingly similar:
String json = ...;
JsonObject jsonObj = (JsonObject) new JsonParser().parse(json);
jsonObj.addProperty("hey", "yow!");
json = jsonObj.toString();

Categories