I have implemented Volley and Recycler view to parse and display a list of few items from a simple JSON file.
There are at times when a key doesnot exists in an object but may appear in other object. That key is already defined using object.getInt("someKey").
As soon as Volley starts parsing the object with the missing key, it breaks out of the for loop (objects are stored in array) and catches the JSONException e, which is exactly what the app is supposed to do in case of a missing key.
However, I would like to prevent this behavior and use a placeholder value for that missing key of that particular object, so that the array list gets successfully buildup and recyclerview gets filled thereby application starts working normally.
What logic can I use in order to achieve this behavior?
Thank you!
private void parseJSON() {
String url = "https://example.com/index.json";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String title = object.getString("subject");
String description = object.getString("message");
String imageUrl = object.getString("thumb");
Integer threadId = object.getInt("threadId");
mList.add(new Item( title, description, threadId));
}
mItemAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
In the above code, threadId is the key, which may or maynot appear in many objects of the JSON.
You can check firstly if your key exists on object
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String title = object.getString("subject");
String description = object.getString("message");
String imageUrl = object.getString("thumb");
Integer threadId;
if(object.toString().contain("threadId"){
threadId = object.getInt("threadId");
}else{
threadId = 0;
}
mList.add(new Item( title, description, threadId));
}
mItemAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
If i understood well your Question , here what you need to do , if you are not sure if this key exists use the following
jsonObject.optBoolean("yourKey");
jsonObject.optInt("yourKey");
jsonObject.optString("yourKey");
jsonObject.optLong("yourKey");
jsonObject.optDouble("yourKey");
jsonObject.optJSONArray("yourKey");
this will make sure jsonObject will ignore that key if it doesn't exist.
object.getInt("someKey") is to get value from "somekey".if somekey is not appeared it shows JSONException. Instead of this object.optInt("someKey"). It will get value from "somekey" if it appears, otherwise it skipped. This is simple solution. Thanks
Related
For learning purposes i'm creating an android app by using Realm and the Edinburg Festival Api. It's going pretty well except for one problem.
I'm using the following to convert the retrieved JSON to RealmObjects:
public void onResponse(final String response) {
realm.executeTransactionAsync(new Realm.Transaction(){
#Override
public void execute(Realm realm) {
// Update our realm with the results
parseImages();
realm.createOrUpdateAllFromJson(Festival.class, response);
}
}
}
This works fine except for one field, the images. The image part of the JSON:
"images": {
"031da8b4bad1360eddea87e8820615016878b183": {
"hash": "031da8b4bad1360eddea87e8820615016878b183",
"orientation": "landscape",
"type": "hero",
"versions": {
"large-1024": {
"height": 213,
"mime": "image/png",
"type": "large-1024",
}
"width": 1024
}
}
The problem here is the hash inside the image object. I have no clue how to handle this. The hash is different for every festival. Would it be possible to to make a custom JSON deserializer in my RealmObject?
Last code sample is my current model:
public class Festival extends RealmObject {
#PrimaryKey
public String title;
RealmList<Image> images;
public String description_teaser;
public String description;
public String genre;
public String age_category;
public String website;
public RealmList<Performance> performances;
public int votes;
}
I'm aware my PK is not optimal but this is still just testing to get the images working and i needed to set a PK for migrating.
Any tips are welcome, cheers :)
Update
Added the image model:
public class Image extends RealmObject {
public String hash;
public String orientation;
public String type;
RealmList<Version> versions;
}
Update 2
My attempt to parse the images before calling realm.createOrUpdateAllFromJson(Festival.class, response);
private void parseImages(String jsonString) throws JSONException {
JSONArray jsonArr = new JSONArray(jsonString);
for(int i = 0; i < jsonArr.length(); i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
JSONObject images = (JSONObject)jsonObj.get("images");
Iterator<String> iter = images.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = json.get(key);
realm.createOrUpdateObjectFromJson(Image.class,value);
} catch (JSONException e) {
// Something went wrong!
}
}
}
}
Update 3
I created a function that cleans up the broken JSON i get from the API. It ain't very nice but it works for now. it removes the hashes and the wierd versions and just places them both in a array. I'm sure it could be more efficiently written but i'll just go with this so i can move on with the rest of my app for now. See my own answer.
my own temporary solution:
/**
* Function to fix the json coming from the Festival API
* This is a bit more complicated then it needs to be but realm does not yet support #Serializedname
* It removes the "large-1024" (and simllar) object and places the versions in a JSON version array
* Then it removes the hashes and creates and images array. The JsonArray can now be parsed normally :)
*
* #param jsonString Result string from the festival api
* #return JSONArray The fixed JSON in the form of a JSONArray
* #throws JSONException
*/
private JSONArray cleanUpJson(String jsonString) throws JSONException {
JSONArray json = new JSONArray(jsonString);
for(int i = 0; i < json.length(); i++){
// We store the json Image Objects in here so we can remove the hashes
Map<String,JSONObject> images = new HashMap<>();
JSONObject festivalJson = json.getJSONObject(i);
JSONObject imagesJson = (JSONObject)festivalJson.get("images");
// Iterate each hash inside the images
Iterator<String> hashIter = imagesJson.keys();
while (hashIter.hasNext()) {
String key = hashIter.next();
try {
final JSONObject image = imagesJson.getJSONObject(key);
// Remove the version parents and map them to version
Map<String, JSONObject> versions = new HashMap<>();
JSONObject versionsJsonObject = image.getJSONObject("versions");
// Now iterate all the possible version and map add to the hashmap
Iterator<String> versionIter = versionsJsonObject.keys();
while(versionIter.hasNext()){
String currentVersion = versionIter.next();
versions.put(currentVersion,versionsJsonObject.getJSONObject(currentVersion));
}
// Use the hashmap to modify the json so we get an array of version
// This can't be done in the iterator because you will get concurrent error
image.remove("versions");
Iterator hashMapIter = versions.entrySet().iterator();
JSONArray versionJsonArray = new JSONArray();
while( hashMapIter.hasNext() ){
Map.Entry pair = (Map.Entry)hashMapIter.next();
versionJsonArray.put(pair.getValue());
}
image.put("versions",versionJsonArray);
Log.d(LOG_TAG,image.toString());
} catch (JSONException e) {
e.printStackTrace();
}
images.put(key,imagesJson.getJSONObject(key));
}
// Now let's get rid of the hashes
Iterator hashMapIter = images.entrySet().iterator();
JSONArray imagesJsonArray = new JSONArray();
while( hashMapIter.hasNext() ){
Map.Entry pair = (Map.Entry)hashMapIter.next();
imagesJsonArray.put(pair.getValue());
}
festivalJson.put("images", imagesJsonArray);
}
return json;
}
Hope it helps someone :) But sure ain't neat.
Due to how the keys are dynamic in this JSON (why isn't this an array? Whoever designed this API had no idea what they were doing), you'll have to manually parse the object up to the point of the hash key:
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject images = (JSONObject)jsonObj.get("images");
Iterator<String> iter = images.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = json.get(key);
realm.createOrUpdateObjectFromJson(Image.class, value.toString());
} catch (JSONException e) {
// Something went wrong!
}
}
I have successfully Integrated Volley library into my android studio project and got below responses. Now I need to get particular values from below response. I need to GET (A, B, C, D, E,etc,.. )values and related boys and girls values also. Once I got it I need to list out on list view like below model.
I am expecting :
-----------------------------------------
Title Boys Girls
-----------------------------------------
A 1.5 3.5
-----------------------------------------
B 1.5 3.5
-----------------------------------------
Below My Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Displays Home Screen
setContentView(R.layout.activity_list);
//displaying TextView
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "MYURL";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
txtDisplay.setText("Response => "+response.toString());
System.out.println("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
}
Below My Response :
{
"response":{
"A":{
"boys":1.5,
"girls":"3.5",
},
"B":{
"boys":1.5,
"girls":"3.5",
},
"E":{
"boys":1.5,
"girls":"3.5",
}
},
"schools":{
},
"distances":"172 KM"
}
use following code to get values:
JsonObject json = response.get("response");
String a =json.get("A").toString();
similarly find other values;
eg;
when you get
JsonObject json = response.get("response");
then the json will be :
{
"A":{
"boys":1.5,
"girls":"3.5",
},
"B":{
"boys":1.5,
"girls":"3.5",
},
"E":{
"boys":1.5,
"girls":"3.5",
}
}
and if you want to get A / B/ C from this json use
jsonA = json.get("A");
{
"boys":1.5,
"girls":"3.5",
}
if you want to retrive boys from A
then
String boys = jsonA.get("boys").toString();
similarly
json.get("B");
and
json.get("C");
In order to get the string from the json object you can use the following
JSONObject jObj=new JSONObject(response.toString());
for boys of type a
String a = jObj.getJSONObject("response").getJSONObject("A").getString("boys").toString();
for girls of type a
String b = jObj.getJSONObject("response").getJSONObject("A").getString("girls").toString();
run the follwoing lines in a loop and store them according to your needs
I got it myself, What I am expected.
JSONObject data = response.getJSONObject("response");
Iterator keys = data.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = data.getJSONObject(currentDynamicKey);
// do something here with the value...
}
I am working on parsing data from a JSON url.
But the JSONobjects have different keys.
I want to get all the data from each json object and when it doesn't have that key I want to give it a default message.
This is what I'm trying to use:
if(myJSONObject.has("mykey")) { <- in this case "abv"
//it has it, do appropriate processing
}
I got this variable
private static final String TAG_ABV = "abv";
I tried doing this to check if the abv key was included in the JSON and give the string a default text of "No value" when it was not inculed.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
if(c.has("abv")) {
String abv = c.getString(TAG_ABV);
} else {
String abv = "No value";
}
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ABV, abv);
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
But I have this error: cannot find symbol variable abv
I guess the abv inside the if statement is out the scope.
You're declaring abv inside the if/else blocks, which means it's only accessible inside that block. When you try to use it later (in data.put(TAG_ABV, abv); the variable you created is no longer accessible - it's out of scope. If you move the declaration of abv to the line before the if/else statement, that should fix your error.
The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.
As the title says really. I have two columns. I want to put them into textviews so I did it. However only the bottom two results, one from each column gets shown. Very odd. Here is my code: http://pastebin.com/qNgfHfT3
The parsing/onPostExecute is towards the bottom where the issue is.
One thing to note: The logs labeled "work" & "dontwork" show all my results, however the logs in the onPostExecute (Google & Google1) only show the last result so I presume the error is in the transfer from parsing to displaying.
Would really appreciate any help here. Thanks.
If you are receiving a JSON response I'd suggest you to parse it by using Gson. It's strongly recommendable as long as you can parse the whole thing in a pair of lines.
Note that creating a proper object it is as easy as doing the following:
YourObject object = gson.fromJson(responseReader, YourObject.class);
or even if you are retrieving a list of items:
Type listType = new TypeToken<List<YourObject>>() {}.getType();
List<YourObject> objects = gson.fromJson(responseReader, listType);
Here's an example that fits exactly your needs
After the process is done you'll have your object (or list of objects) available in an accesible variable.
EDIT:
First your Asynctask should have the following params:
public class HttpTask extends AsyncTask<Void, Void, ArrayList<Driver>> {
and your doInBackground method will need to pass that array to your onPostExecute:
#Override
protected ArrayList<Driver> doInBackground(Void... params) {
For the rest, I take it when the JSon parsing starts.
//PARSING JSON DATA
try {
JSONObject json_data;
Driver d;
jArray = new JSONArray(result);
int l = jArray.length();
if(l>0){
ArrayList<Driver> drivers = newArrayListList<Driver>();
for (int i = 0; i < l; i++) {
json_data = jArray.getJSONObject(i);
d = new Driver(json_data.optString("Driver_full_name"), json_data.optString("Drives_for"));
drivers.add(d);
Log.i("work", returnString);
Log.i("dontwork", somethingelse);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
CurrentSeasonDrivers_DriverName.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(CurrentSeasonDrivers_DriversName, "Could not parse data so shut up", Toast.LENGTH_LONG).show();
}
});
}
return drivers;
}
protected void onPostExecute(ArrayList<Drivers>... drivers) {
Log.i("Google", returnString);
Log.i("Google1", somethingelse);
String firstDriverName = drivers.get(0).name;
String firstDriverDrivesFor = drivers.get(0).drivesfor;
String secondDriverName = drivers.get(1).name;
TextView drivername = (TextView) findViewById(R.id.DriverName);
drivername.setText(firstDriverName);
TextView drivesfor = (TextView) findViewById(R.id.DrivesFor);
drivesfor.setText(firstDriverDrivesFor);
}
With this and an object for your driver will complete the circle.
public class Driver{
public String name;
public String drivesfor;
public Driver(String _name, String _drivesfor){
name = _name;
drivesfor = _drivesfor;
}
}
I guess you can take over from here.
Let me know about your progress.