Reputation: 117
I am under the gun on this one (about 6 hours to get this working) and I know I'm missing something completely simple here.
I am trying to parse a JSON response with a single piece of data, but my parse code isn't picking it up.
Here is the entire JSON response...
{"id":"4480"}
The "4480" is a potential alpha-numeric data response, so it could be something like "A427" as well.
Here is the code I am using to try to parse the single response. The problem is that userID is null - it's not picking up the 4480 in the JSON response. Could someone please point out where I'm messing this up? Many thanks in advance for any help I can get!!
InputStream is = null;
//http post
try{
String postQuery = "my api post goes here";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postQuery);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
JSONObject userObject = new JSONObject(result);
JSONObject jsonid = userObject.getJSONObject("id");
userID = jsonid.getString("id");
}
Upvotes: 2
Views: 6873
Reputation: 190
Try this code:
try{
final JSONObject jsonObject = new JSONObject(result);
if (jsonObject.length() > 0)
{
String userID = jsonObject.optString("id");
Log.e("TAG", "userID:"+ userID);
}
}catch (Exception e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 100398
I'm not really familiar with JSON parsing, but based on this example, I think you should change the //parse json data
into this:
//parse json data
try {
JSONObject userObject = new JSONObject(result);
userID = userObject.getString("id");
} catch(Exception ex){
//don't forget this
}
That is if the call to new JSONObject(result)
is correct. Previously mentioned example shows something like this:
JSONObject userObject = (JSONObject) JSONSerializer.toJSON( result );
Upvotes: 7