I am trying to parse the following JSON in Java program.
JSON
{
"data": {
"pageIDentifier":" nametitle",
"page": {
"pageID”:” sports_league_member",
"platform":" www",
"activityType":" ent",
"businessUnit":" ent",
"productLOB":" ent",
"productOffered":" abc",
"productQualifier”:” abc:a bc”,
"flowType”:” sports_com”,
"pageDesc”:” desc”,
"attributes": {
"pageType":" www",
"host”:” finaluser”,
"appId”:” SportsAppID_user”,
"daEnvironment”:” releaser”,
"jvm":" ent_logon_01",
"xCKey":" SportsAppID_user",
"daUID":" jddc9yu5pi1yy6",
"sysEnv”:” user”,
"uri”:” /www/sportscenter”,
"daPageName":" "
}
}
}
}
JAVA Program
URL url = getClass().getResource("test.json");
File file = new File(url.getPath());
String jsonData = readFile(file.getAbsolutePath());
JSONObject jobj = new JSONObject(jsonData);
JSONArray jarr = new JSONArray(jobj.getJSONArray("data").toString());
System.out.println("jarr: " + jarr);
I am getting the following error when executing this code. Please note, jsonData is giving the entire json string without any issue.
org.json.JSONException: JSONObject["data"] is not a JSONArray.
How can i parse "data" value from the above json value? Please advise.
data is not an array
Try this :
System.out.println("jarr: " + jobj.getJSONObject("data").toString());
Related
I have following json data
{
"TestMetrics": {
"ProcessPID": "7887",
"MemSwapped": "0",
"Uptime": "407",
"webTiming": "{\"domainLookupStart\":3,\"domainLookupEnd\":67}"}
}
From this i need to fetch the webTiming json object.
For that i used following code
JSONObject launchMetricsObj = new JSONObject(jsonData);
try {
JSONObject objc = launchMetricsObj.getJSONObject("TestMetrics");
JSONObject webtimingObj = objc.getJSONObject("webTiming");
System.out.println(webtimingObj:::::: " +webtimingObj);
} catch (JSONException e) {
System.out.println("Exception:" + e);
}
As the "webTiming" value is a JSONObject i tried to get it as
JSONObject webtimingObj = objc.getJSONObject("webTiming");
But I observed following Exception:
JSON Objectorg.codehaus.jettison.json.JSONException: JSONObject["webTiming"] is not a JSONObject.
It's because webTiming is defined as a string, not JSONObject.
In order to convert it, you need to do:
JSONObject webtimingObj = new JSONObject(objc.getString("webTiming"));
I want to parse the JSON data by removing the backslash from the JSON format.
I have tried removing the backslash from the JSON format by the following code but nothing worked out
JSONArray packsJSON = new JSONArray();
JsonObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JsonObject();
innerObject.addProperty("pack_id",packageList.getSubs_id());
innerObject.addProperty("pack_dsc", packageList.getSubs_desc());
innerObject.addProperty("pack_tax_amt", packageList.getTax_amnt());
innerObject.addProperty("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}
output of INNEROBJECT:
{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}
The output of PACKJSON:
[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}",
"{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"
]
[
"{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}",
"{"pack_id":"2232","pack_dsc":"Bangara(280)","pack_tax_amt":"0","pack_grand_total":"280"}"
]
Your JSONArray is of org.json package and JsonObject is of com.google.gson package
so your innerObject's type should be org.json.JSONObject
JSONArray packsJSON = new JSONArray();
JSONObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JSONObject();
innerObject.put("pack_id",packageList.getSubs_id());
innerObject.put("pack_dsc", packageList.getSubs_desc());
innerObject.put("pack_tax_amt", packageList.getTax_amnt());
innerObject.put("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}
Please check below answer.
String jsonString = "[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}","{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"]"
String outputString = jsonString.replaceAll("\\\\", "");
Log.e("Clear String :", outputString);
OUTPUT
So I get place_id by storing it in a Hashmap with the "name" of the place as the key.
private HashMap<String, String> placeTitleId = new HashMap<>();
if (!place.isNull("place_id")) {
placeId = place.getString("place_id");
placeTitleId.put(name, placeId);
}
Later, I create the Places Detail search url:
private String createPlaceDetailsUrl(String placeId) {
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?");
stringBuilder.append("placeid=").append(placeId);
stringBuilder.append("&key=").append(GOOGLE_PLACES_API_KEY);
return stringBuilder.toString();
}
Finally, I parse the json response:
JSONObject data = new JSONObject(result);
if (data.getString("status").equalsIgnoreCase("OK")) {
JSONArray photoArray = data.getJSONArray("photos");
}
What I don't understand is why the "photos" json array has no value
Android Monitor: W/System.err: org.json.JSONException: No value for photos
The documentation says that the photos[] jsonarray should have up to 10 photos. However, the json output schema does not contain a photos[] object, which I find weird. Is there a problem with how I am obtaining place_id or parsing the response?
EDIT:
The "result" String is incredibly long, but I can provide a gist:
result {
"address components" : [
*bunch of stuff*
]
...
"geometry" : {
*bunch of stuff*
}
"icon"
"id"
"photos" : [
{
"height"
"html_attributions:
"photo_reference!!
}
{
...
"photo_reference!!
}
*bunch more of these*
]
}
EDIT:
Fix is getting json object "result
JSONObject jsonObject = new JSONObject(result);
JSONObject data = new JSONObject("result");
The data object has "pictures"
Try this.
JSONObject data = new JSONObject(result);
// add log here ,make sure you have photos in your result
Log.e("result", result + "");
if (data.getString("status").equalsIgnoreCase("OK")) {
// edited here
JSONArray photoArray = data.optJSONArray("photos");
}
Edit
if (data .has("photos")) {
Log.e("photos", "photos exists");
} else {
Log.e("photos", "photos not exists");
}
Use data .has("photos") in your code and judge it .
Note
Use
JSONObject data = new JSONObject(result);
if(data.has("TAG")){
// if has it in your data,do something
}
to determine whether this tag is present in the data
I need a help... I have a php file which returns me two json Arrays which are as follows:
[{ "id":"1",
"item":"hammers",
"aisle":"20"
}
{ "id":"1",
"item":"hammers",
"aisle":"20"
}]
[{ "id":"1",
"itemFound":"Your item #item",
"ThankYou":"and Thank You for using Txtcore!"
}]
Now, I want to get the second array items in Android. I have the following code now which is like :
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(jsonObject.getString("item"));
aisles.add(""+jsonObject.getString("item");
}
But obviously, that returns me the objects from the first array. I want to get the Objects from the second array. Any suggestions.
Your JSON is not valid but u can get your element as follows. It is a solution from many(just a worlaround).
String str = "YOUR_JSON_RESPONSE";
String array[] = str.split("\\[\\{");//
try {
JSONArray jsonArray=new JSONArray("[{" + array[2]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I guess you'll have to do some dirty coding because the data return by the PHP page is not well formed JSON.
You could try to transform the JSON data to:
{ "data" : [ <array_1>, <array_2> ]} And then use the JSON parser. A simple replacement with a regexp could be fine.
result.replaceAll("\\]\\s*\\[", "], [");
StringBuffer buffer=new StringBuffer(result);
buffer.insert(0,"{ \"data\": ");
buffer.append(" }");
JSONObject jsonObject = new JSONObject(buffer.toString());
JSONArray secondArray= jsonObject.getJSONArray("data").getJSONArray(1);
The creation of a valid JSON string can be done in one step with the appropriate regexp. Hope some one with more time can post it here.
I have the following code:
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonObject json = parser.parse(gson.toJson(roomList)).getAsJsonObject();
System.out.println("json: " + json);
It gives me the following output:
gson.toJson: [{"id":"8a3d16bb328c9ba201328c9ba5db0000","roomID":9411,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328b9f3a01328b9f3bb80000","roomID":1309,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328ba09101328ba09edd0000","roomID":1304,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bb8af640000","roomID":4383,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd271fe0001","roomID":5000,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd2e0e30002","roomID":2485,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3087b0003","roomID":6175,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd35a840004","roomID":3750,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd366250005","roomID":370,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3807d0006","roomID":9477,"numberOfUsers":4,"roomType":"BigTwo"}]
json2: {"b":"c"}
java.lang.IllegalStateException: This is not a JSON Object.
Can someone please help me parse my Json string to JsonObject? I have checked in http://jsonlint.com/ that my json is valid though.
It's because due to the JSON structure..
I have to put it into a JSONObject first, like so
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(ServerConstants.JSONoutput, gson.toJson(roomList));
Then I would deserialize like
List<RoomData> roomList = gson.fromJson(jsonObj.get(CardGameConstants.JSONoutput).toString(), listType);
for (RoomData roomData : roomList) {
System.out.println(roomData.getRoomID());
}
This should give you some basic idea.
ArrayList<String> roomTypes = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for(int i =0; i<jsonArray.length(); i++){
roomTypes.add(jsonArray.getJSONObject(i).getString("roomType"));
}
The problem with the code is that roomList is not a JsonObject as evident in the printed output. It's actually a JsonArray.
To fix the code, call .getAsJsonArray() (instead of .getAsJsonObject())
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonArray json = parser.parse(gson.toJson(roomList)).getAsJsonArray();
System.out.println("json: " + json);