Paul Clapham wrote:
peter pham wrote:I understand completely what's happening. I am consuming a publicly available API. I am getting stores in a zip code. 18/20 of the stores have all the json attributes, the other 2 don't. Why? I don't know and I'm not supposed to know, a stranger provided this data. The problem is as simple as the one json attribute, say "distance", is not available for store #10, so an exception is thrown and the parsing of the other json attributes is not accomplished.
So catch the exception and do whatever your business requirements say should be done if the distance is missing.
That's assuming you can catch the exception and identify specifically what attribute was missing. I have no idea whether you can do that or not because you have avoided posting any detailed information which tells us that. My guess is that it's the line of code Double sDist = sLoc.getDouble("distance"); which is throwing the exception, in which case you could certainly catch the exception there, but even when I asked you about the stack trace you didn't respond to that.
Paul Clapham wrote:If you're getting a JSONParseException, that sounds to me like more than just a missing attribute. I would suggest you look at the JSON which doesn't parse and see what the problem is with it.
Winston Gutkowski wrote:
peter pham wrote:I have an android application that consumes a REST API and parses a JSON response. Sometimes the json response is unexpected. For example, if an attribute is missing one day, this could lead to a NPE if not handled properly. To resolve this, I check to see if the parsed value is null to avoid the app crashing from an NPE. That's a lot of if statements in my try block, one for each parsed variable Is there a better way to go about this?
Probably, but first we'd need to know:
1. What version of Java is this Android app using?
2. (probably more important) What do you plan to do if you do get a null value?
And it's that last one that's likely to be the toughest to answer, because there may be more than one depending on which value (or values) is/are null.
If you could also tell us a bit more about why a response might be "unexpected", or why an attribute might be "missing", it might help us to advise. Indeed, if you could tell what this app is doing, you might get responses from people who've been through the same problem.
Campbell Ritchie wrote:Why have you got <= in that for loop?
Why are you mixing Java and pseudo‑code in the same block?
We cannot tell how you should make that list; start by telling us what the algorithm is.
Paul Clapham wrote:It's the BufferedWriter which is clearing your file, not the reader.
Jesper de Jong wrote:What is the return type of the method that you're calling via reflection (or are you calling different methods)? Can you show us your code?