Fetch JSONObject value from a JSON data object - java

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

Related

Parsing JSON fails with not a JSONArray

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

Google Places detail "photos[]" jsonarray is always null

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

parse json array in android

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.

Multiple values for a JSON key

I am a beginner on JSON in Java http://json.org/java/
How can I create a JSON object like this?
{
"RECORD": {
"customer_name": "ABC",
"customer_type": "music"
}
}
Try like this:
JSONObject jsonObject = new JSONObject();
jsonObject.put("customer_name", "ABC");
jsonObject.put("customer_type", "music");
JSONObject jsonObject_rec = new JSONObject();
jsonObject_rec.put("RECORD", jsonObject);
System.out.println(jsonObject_rec);
You have to make "RECORD" an JSONobject. This is an example:
JSONObject json = new JSONObject();
// Add a JSON Object
JSONObject Record = new JSONObject();
Record.put( "customer_name", "ABC");
Record.put( "customer_type", "music");
json.put( "RECORD", Record);
// P toString()
System.out.println( "JSON: " + json.toString() );

Parse json array from webserver

I'm going to parse a json array from web server to android app.The array looks like this
{"Level":
[
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]},
{"route":[{"lat":38.889762,"lgn":-77.081764},
{"lat":38.89096,"lgn":-77.081916}]}
]
}
my java code is
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("Level");
rlevel = new ArrayList<LatLng>();
System.out.println("*****JARRAY*****"+jArray.length());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
jlat = json_data.getDouble("lat");
jlgn = json_data.getDouble("lgn");}
but not works! any idea?after this i want to save each route into an array (etc $plan[1]=first route from json, $plan[2]=second route from json)
Try something like this:
//code is a String where you saved the json
JSonObject json= new JsonParser().parse(code).getAsJsonObject();
JsonArray jArray= json.getAsJsonArray("Level");
rLevel=new ArrayList<LatLng>();
//notice the use of the size() method. There is not length() method defined for ArrayList
System.out.println("*****JARRAY*****"+jArray.size());
for(int i=0;i<jArray.size();i++){
//notice that inside the Level Array you have route-arrays
JSonObject level_item = jArray.get(i).getAsJsonObject();
JSonArray route= level_item.getAsJSonArray("route");
//now I don't know exactly what data you want to extract, since there are 2
//pairs of LatLng, for the first one:
jlat = route.get(0).get("lat").getAsDouble();
jlgn= route.get(0).get("lgn").getASDouble();
The exact names for methods and JsonObjects tend to differ from a library to another, but the principle is the same.
This parse task can be done very easily using droidQuery:
try {
JSONObject json = $.parseJSON(result);
if (json.has("Level")) {
Object[] datas = $.makeArray(json.getJSONArray("Level"));
for (Object data : datas) {
JSONObject obj = (JSONObject) data;
Object[] coordinates = $.makeArray(obj.getJSONArray("route"));
for (Object coord : coordinates) {
Map<String, ?> map = $.map((JSONObject) coord);
double latitude = (Double) map.get("lat");
double longitude = (Double) map.get("lgn");
//TODO: do something with these values
}
}
}
else {
Log.d("JSON", "Result does not contain 'Levels' variable");
}
}
catch (Throwable t) {
t.printStackTrace();
}

Categories

Resources