Android - JSON Parse Not Showing Data using "setText" - java

I have the following JSON Information.
{
"version": 2,
"locations": [{
"id": "750",
"geo": {
"name": "Lord Howe Island",
"state": "Lord Howe Island",
"country": {
"id": "au",
"name": "Australia"
},
"latitude": -31.557,
"longitude": 159.086
},
"astronomy": {
"objects": [{
"name": "moon",
"days": [{
"date": "2018-09-05",
"events": [],
"moonphase": "waningcrescent"
}]
}]
}
}]
}
What I wish to do is print to a textView just a few details in the JSON (Not All), so my desired output is the following:
Name: Lord Howe Island
Country: Australia
Moon Phase: Waning Crescent
However, I do not have any luck when parsing the information to be printed in the textView. I am currently using the following code:
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
JSONObject geo = JO.getJSONObject("geo");
JSONObject astronomy = JO.getJSONObject("astronomy");
singleParsed = "Name:" + geo.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + astronomy.get("moonphase") + "\n";
}
Then showing the data with the following:
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.fetcheddata.setText(this.singleParsed);
}
}
I can print all of the data just using
MainActivity.fetcheddata.setText(this.data);
However I do also see the tags in the textView and ALL Information, not the few tags I am after.
What Am I doing wrong?
All help is much appreciated
Edit: This was suggested, currently working on it.
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
JSONObject astronomy = JO.getJSONObject("astronomy");
JSONArray objects = astronomy.getJSONArray("objects");
JSONArray days = objects.getJSONObject(0).getJSONArray("days");
Object moonphase = days.getJSONObject(0).get("moonphase");
moon = "Name:" + days.get(Integer.parseInt("moonphase"));
}

The problem you're running into is you're trying to use JSONObjects, even though locations is an array, as is objects.
For this to work, you will need to iterate over the array as such:
JSONObject jo = new JSONObject(yourData);
JSONArray locations = jo.getJSONArray("locations");
for (int i = 0; i < locations.length(); ++i) {
//iterate over each key, etc.
}
In my opinion, at the end of the day, this will be a mess, and a pain to maintain if you change keys, add keys, etc. I'd recommend looking into something like GSON, and then creating just viewmodels of the data you want. In the end you would end up with something as such:
List<T> yourObjects = gson.fromJson(jsonReader, X[].class);
Then you can individually access any property you want.

cannot get moonphase directly from astronomy , [] will define an array, so you could do like this:
"astronomy": {
"objects": [{
"name": "moon",
"days": [{
"date": "2018-09-05",
"events": [],
"moonphase": "waningcrescent"
}]
}]
}
JSONObject astronomy = JO.getJSONObject("astronomy");
JSONArray objects = astronomy.getJSONArray("objects");
JSONArray days = objects.getJSONObject(0).getJSONArray("days");
JSONObject moonphase = days.getJSONObject(0).get("moonphase");

Assuming your json data as it is and your output as you wrote above:
JSONArray locations = data.getJSONArray("location");
JSONObject loc = locations.getJSONObject(0);
JSONObject geo = loc.getJSONObject("geo");
JSONObject country = geo.getJSONObject("country");
JSONObject astronomy = loc.getJSONObject("astronomy");
JSONObject objects = astronomy.getJSONArray("objects").getJSONObject(0);
JSONObject day = objects.getJSONArray("days").getJSONObject(0);
StringBuilder result = new StringBuilder();
String singleParsed = "Name:" + geo.getString("name") + "\n" +
"Country: " + country.getString("name") +
"Moon Phase: " + astronomy.getString("moonphase") + "\n";

Related

JSONException: No value for myRating even when value exist on same node

My app was working fine but suddenly it start giving me erros JSONException: No value for myRating. I know it's means the value doesn't exist on JSON but i cross check dozens times that myRating exist in JSON i received and i am also able to get other values from same node.
Here is my JSON
{
"status": "SUCCESS",
"uData": [
{
"User_ID": "210",
"First_Name": "Alex ",
"Image": "947d051925ba2014f231f17ffc04db6616645163211632870246.jpg",
"coverPhoto": "1ce295d101204be40363f1e11301ed97d41d8cd98f00b204e9800998ecf8427e16645163211188778355.jpg",
"Gender": "Male",
"login_status": "0",
"myRating": "5.00",
"coverImageID": "354",
"ProfileImageID": "343",
"show_onlineStatus_check": "1",
"verify": "1"
},
{
"User_ID": "4",
"First_Name": "John",
"Image": "cf867d87b655591cbda928287da1ca3616520548151008802.jpg",
"coverPhoto": "0323e6cfa77488abce52aa273e2f5f8e16523048561229563452.jpg",
"Gender": "Female",
"login_status": "0",
"myRating": "5.00",
"distance_check": "1",
"coverImageID": "173",
"ProfileImageID": "174",
"show_onlineStatus_check": "1",
"verify": "2"
}
],
"record": 3,
"uCounter": "50"
}
That's how i am parsing JSON into my app
JSONObject parentArray = new JSONObject(completeJSON);
Log.d(TAG, "Parent Array " + parentArray);
JSONArray jsonArray = parentArray.getJSONArray("uData");
String profileCounter = parentArray.getString("uCounter");
Log.d(TAG, "JSON Array Of UDATA " + jsonArray); // User Data Where I have myRating node
String ImageURL, UserID, Distance, CoverPhoto, myRatings = null;
int Rec_Online_Status;
int distance_check, onlineStatus, verifyProfile;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childObject = jsonArray.getJSONObject(i);
String Fname = childObject.getString("First_Name");
ImageURL = childObject.getString("Image");
CoverPhoto = childObject.getString("coverPhoto");
UserID = childObject.getString("User_ID");
String gender = childObject.getString("Gender");
Rec_Online_Status = childObject.getInt("login_status");
distance_check = Integer.parseInt(childObject.getString("distance_check"));
onlineStatus = Integer.parseInt(childObject.getString("show_onlineStatus_check"));
verifyProfile = Integer.parseInt(childObject.getString("verify"));
boolean testValue = childObject.has("myRating");
Log.d(TAG, "doInBackground: Test Log = "+testValue);// This also return False
myRatings = childObject.getString("myRating");// JSONException: No value for myRating
int profileID = Integer.parseInt(childObject.getString("ProfileImageID"));
int coverID = Integer.parseInt(childObject.getString("coverImageID"));
}
I am really not sure what i am doing wrong and when value exist in same node it should get fetched but as you can see i am getting exception. Can anyone help me out in this. The is required to run app so i am not using has or optString.

How to extract specific fields of JSON Array in Java and store it in String

I have JSON data and want to extract data of only specific fields in Java and store it in String.
Example,
From issues, key:651, From project name:test, updated, created This details for all records of array issues.
Sample JSON Data:
"issues": [
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "651",
"fields": {
"project": {
"name": "test",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
},
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "321",
"fields": {
"project": {
"name": "test2",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
}
]
Java code that I have tried so far jar used - (gson-2.8.5)
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
JsonObject issues0data = (JsonObject) issues0.get("key");
String issue_key = issues0data.get("issue_key").getAsString();
System.out.println("Value of key is -> " + issue_key); // java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
Updated Code
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues_data = (JsonArray) object.get("issues");
for(int i=0; i<issues_data.size(); i++)
{
JsonObject issues = (JsonObject) issues_data.get(i);
String issues_key = (String) issues.get("key").toString();
String project_name = (String) issues.get("name").toString(); // returns null
}
You can convert to string when you get the value.
Change your code like this see if it helps.
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
String issue_key = (String) issues0.get("key");//<---here
System.out.println("Value of key is -> " + issue_key);
Update
If you want all values just put it inside "for":
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
Update 2
The data "updated" and "created" are not inside "issues" they are inside "fields" to get access to them you need to get them from "fields". You have to go inside level by level to get access to variables:
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
JsonObject fields = (JsonObject) issues.get("fields");
JsonObject project = (JsonObject) issues.get("project");
String project_name = (String) project.get("key");
String fields_updated = (String) fields.get("updated");
String fields_created = (String) fields.get("created");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
You are getting an error because you are casting a JsonPrimitive to JsonObject. So instead of using
JsonObject issues0data = (JsonObject) issues0.get("key");
you should do
String issues0data = issues0.get("key").getAsString();
System.out.println("Value of key is -> " + issues0data);
Here, calling getAsString() will invoke JsonPrimitive.getAsString() method. This will take care if the primitive is boolean/number/string and convert it to string.

How to fetch column name which is not in JSON but still it is an array element that i have received using PHP in android

How can a column name, which is not in JSON but still it is an array element that I have received using PHP in android, be fetched?
This is my PHP file:
{
"items": [
{
"v_id": "1",
"v_name": "Hotel Girija",
"v_address": "Vijayanagar Colony, Municipal Colony, Pune, Maharashtra 411030",
"v_avg_rating": "3",
"v_image": "http://i1.walesonline.co.uk/whats-on/food-drink-news/article7978981.ece/ALTERNATES/s615/MAin.jpg",
"v_contact1": "8456217412"
},
{
"v_id": "4",
"v_name": "Pataleshwar hotel",
"v_address": "Some addresss again",
"v_avg_rating": "5",
"v_image": "https://www.whatsuplife.in/gurgaon/blog/wp-content/uploads/2015/09/Chaat-Chowk.jpg",
"v_contact1": "5452232554"
}
],
"sub_image": "http://www.asiansinamerica.org/wp- content/uploads/2016/08/Asian-and-Chinese-Food.jpg",
"success": 1
}
I have to get all values of key items using this :
JSONObject root = new JSONObject(items);
JSONArray arr = root.getJSONArray("items");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj = (JSONObject) arr.get(i);
path = "" + obj.optString("v_image");
// path = "http://" + path.replaceAll("\\s+", "%20");
al_subcatdetl_id.add("" + obj.optString("v_id"));
al_subcatdetl_name.add("" + obj.optString("v_name"));
al_subcatdetl_addr.add("" + obj.optString("v_address"));
al_subcatdetl_img.add("" + path);
al_subcatdetl_rating.add("" + obj.optString("v_avg_rating"));
///al_subject_img.add(obj.getString("sub_image"));
}
But i don't have any idea how to fetch sub_image, which is outside of items. How can this be achieved?
In these case you can directly get string from JSONObject
try {
JSONObject root = new JSONObject(items);
String subimage = root.getString("sub_image");
} catch(Exception ex){
}

Parsing jsonobject when entire json is an array?

I am using gson-2.5 for this. There is a slight difference in the format of these two jsons, where in the first one;
"usethis": [
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
I would have parsed this to get "text" this way, and everything would be ok;
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(listcontents);
JsonObject rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("usethis").getAsJsonArray();
for(int i = 0; i < items.size(); i++) {
JsonObject item = items.get(i).getAsJsonObject();
String thetext = item.get("text").getAsString();
System.out.println("text: " + thetext + "\n");
}
The difference is that in the second one, I have nothing to get as the rootobject unlike in the first where I used "usethis";
[
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
And setting
rootobj.get("usethis").getAsJsonArray();
to
rootobj.get("").getAsJsonArray();
just gives me an error. How would I be able to parse the second json?
JsonElement is just a superclass of JsonArray and JsonObject.
JsonArray items = root.getAsJsonArray();
should do what you want.

Jsonobject and Jsonarray management In Iteration

I am trying to send the details of Usrs and its items with json. But at time of json genertion, with iterated jsonarry with json object, i stuck t middle.how to manage Jsonrray and JsonObject for below given Iterated data.
{
"Data":
{
["user":1],
"items":
[{"item":1},{"item":2},{"item":3},{"item":4}]
},
{
["user":2],
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
{
["user":3],
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
}
I am not sure, whether above given structure is perfect or not?
if perfect then how can I retrieve particular users 4th item?
I feel bad while writing (non-challenging) code for you, but I had my IDE open, and waiting for coffee. So, code for you.
String s = "{\"Data\":[{\"user\":1,\"items\":[{\"item\":1},{\"item\":2},{\"item\":3},{\"item\":4}]},{\"user\":2,\"items\":[{\"item\":11},{\"item\":2},{\"item\":3},{\"item\":4}]},{\"user\":3,\"items\":[{\"item\":11},{\"item\":2},{\"item\":3},{\"item\":4}]}]}";
JSONObject json = new JSONObject(s);
JSONArray data = json.getJSONArray("Data");
for(int i=0; i< data.length(); i++){
JSONObject userData = data.getJSONObject(i);
if(userData.getInt("user") ==2 ){
JSONArray items = userData.getJSONArray("items");
JSONObject item = items.getJSONObject(3);
System.out.println("item#4: " + item.getInt("item"));
}
}
The correct JSON for you is
{
"Data":[
{
"user":1,
"items":
[{"item":1},{"item":2},{"item":3},{"item":4}]
},
{
"user":2,
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
{
"user":3,
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
}
]
}

Categories

Resources