Android JSON parse error with date - java

Having problems parsing this JSON data in my Android App :
[{"personid":20,"personName":"Ross Gallagher update3","email":"ross_gallagher#rossgallagher.co.uk","birthday":{"date":"2013-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"anniversary":{"date":"1900-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"Credit":2}]
The error I am getting is:
W/System.err: org.json.JSONException: Value [{"birthday":{"date":"2013-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"anniversary":{"date":"1900-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"email":"ross_gallagher#rossgallagher.co.uk","personName":"Ross Gallagher update8","Credit":2,"personid":20}] of type org.json.JSONArray cannot be converted to JSONObject
My JSON Parser code is:
public JSONObject getJSONFromUrl(String url)
{
HttpEntity httpEntity = null;
JSONObject respObject = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(httpEntity != null){
try {
respObject = new JSONObject(EntityUtils.toString(httpEntity));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//....
}
// return JSON
return respObject;
}
All I need is to pull out the Birthday details from this JSON object along with the name, email, credits and anniversary.
Any advice would be appreciated!

Change
respObject = new JSONObject(EntityUtils.toString(httpEntity));
to
respObject = new JSONArray(EntityUtils.toString(httpEntity));
ofcourse respObject has to be an JSONArray

The problem is with your JSON String. You need to remove the square brakets [] .
Square brakets are used to refer array elements. The JSON parser will try to convert it as array object as json data are inside square braket.
Accept my answer if it helps you.

Since the object you are trying to parse is actually a JSONArray and not JSONObject.. So you get JSONObject from that JSONArray like
JSONArray jsonArray = new JSONArray(EntityUtils.toString(httpEntity));
JSONOject jsonObject = jsonArray.getJSONObject(0);
from this jsonObject you would get birthday details...

Related

Android: JSONParser returns NullPointerException

I've read many other topics on SO from people who received the same exception, but none of the proposed solutions worked. So here's my problem:
I'm trying to download a userlist from my database through a function in my app. The JSONParser keeps returning a NullPointException on this particular table from the database. I've successfully used the JSONParser class on other queries, but it doesn't work on this one. I've tested the PHP file which handles the query, and it returns the exact values I want as a JSON OBject. If the table is empty, it returns:
{
"success":0,
"message":"No users found"
}
If the table contains user information, it returns:
{
"success":1,
"users":[
{
"ID":someID1,
"NAME":someName1
"PHONE":somePhoneNumber1
},
{
"ID":someID2,
"NAME":someName2
"PHONE":somePhoneNumber2
}]
}
I'm starting the request by calling
LoadAllUsers load = new LoadAllUsers();
load.execute();
in a certain method. This is my LoadAllUsers class:
public class LoadAllUsers extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(allUsers.this);
pDialog.setMessage("Laden van alle gebruikers...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... args) {
updateJSONData();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
I receive a NullPointerException on the first line of my updateJSONdata() method, which is:
public void updateJSONData() {
JSONObject json = jParser.getJSONFromUrl(my_url);
try {
int success = json.getInt("success");
if (success == 1) {
JSONArray users = json.getJSONArray("users");
for (int i = 0; i<users.length(); i++) {
JSONObject c = users.getJSONObject(i);
String id = c.getString("ID");
String name = c.getString("NAAM");
String phone =c.getString("TELEFOON");
HashMap<String,String> map = new HashMap<String, String>();
map.put("ID",id);
map.put("name",name);
map.put("phonenumber",phone);
if (phoneNumber == phone) {
ID = Integer.parseInt(id);
this.name = name;
}
userlist.add(map);
}
} else {
Log.d("Geen succes!", "Helaas!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
So, the exception is thrown in the line with jParser.getJSONFromUrl(...).
My JSONParser class, of which jParser is an instance, is:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
Log.d("Gemaakte paramstring",paramString);
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("httpResponse: ",httpResponse.toString());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And the LogCat message is:
05-07 10:46:24.995 27615-27686/com.example.user.my_app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.user.my_app, PID: 27615
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.user.my_appcenter_tile.updateJSONData(center_tile.java:376)
at com.example.user.my_app.center_tile$Memberlist.doInBackground(center_tile.java:419)
at com.example.user.my_app.center_tile$Memberlist.doInBackground(center_tile.java:406)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
I would be very grateful if you could help me out with this problem.
Well, jParser is null in updateJSONdata().
Make sure to check if it's != null before using it.
And if it should not be null, then fix your code.
Your error is just a NullPointerException.
You can use 'has' keyword to check availability of json keys, then can parse Json to avoid exception,otherwise you can track via Null Pointer exception.
public void updateJSONData() {
JSONObject json = jParser.getJSONFromUrl(my_url);
try {
int success = json.getInt("success");
boolean isAvail=json.has("users");
if (success == 1) {
if(isAvail)
JSONArray users = json.getJSONArray("users");
for (int i = 0; i<users.length(); i++) {
}
}
}
catch(Exception e){
}
}
1. jParser is NULL so use
// make sure my_url has json string in it
// read json first and use in place of my_url
JSONObject jsonObjTokener = (JSONObject) new JSONTokener(my_url).nextValue();
// get success
String isSuccess = jsonObjTokener.getString("success");
// get users
JSONObject mUser = jsonObjTokener.getJSONObject("users");
at that line
2. You did spelling mistake at
String name = c.getString("NAAM");
correct to
String name = c.getString("NAME");

Is it possible to send JSONArray instead of JSONObject via POST?

Most of the answers on SO on the subject revolve around sending all your data inside one JSONObject, with the JSONArrays inside.
I would like to do the opposite, if possible.
Here's some code:
JSONObject winnerJSONObject = new JSONObject();
JSONObject loserJSONObject = new JSONObject();
try{
winnerJSONObject.put(Columns.ID.toString(), winner.getId());
winnerJSONObject.put(Columns.NAME.toString(), winner.getName());
winnerJSONObject.put(Columns.SCORE.toString(),winner.getScore());
winnerJSONObject.put(Columns.WINS.toString(), winner.getWins());
winnerJSONObject.put(Columns.LOSSES.toString(), winner.getLosses());
winnerJSONObject.put(Columns.MAX_SCORE.toString(),winner.getMaxScore());
winnerJSONObject.put(Columns.MIN_SCORE.toString(),winner.getMinScore());
loserJSONObject.put(Columns.ID.toString(), loser.getId());
loserJSONObject.put(Columns.NAME.toString(), loser.getName());
loserJSONObject.put(Columns.SCORE.toString(),loser.getScore());
loserJSONObject.put(Columns.WINS.toString(),loser.getWins());
loserJSONObject.put(Columns.LOSSES.toString(),loser.getLosses());
loserJSONObject.put(Columns.MAX_SCORE.toString(),loser.getMaxScore());
loserJSONObject.put(Columns.MIN_SCORE.toString(),loser.getMinScore());
} catch (JSONException e) {
e.printStackTrace();
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
try {
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(jsonArray.toString(), HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(winnerJSONObject);
jsonArray.put(loserJSONObject);
Why is this a wrong approach?
Yes it is possible.
Example:
Like if we have our data in arraylist to upload on server, Yo can send it in this way
JsonArray _array = new JsonArray()
for(i = 0; i< _arraylist.size(); i++){
JsonObject obj = new JsonObject();
obj.put(_array.list.get(i).getValue);
_array.put(obj);
}
}

Android: httppost Illegal character in query at index

Im trying to parse the json returned from graph facebook, a feed from a page.
The url is something like this: https://graph.facebook.com/pageId/feed?access_token=MyAppId|MySecretKey&limit=10.
But I'm getting the error: Illegal character in query at index 7. The character at index 77 it's the "|". My code:
private JSONObject getJSONFromUrl(String url) throws UnsupportedEncodingException {
// Making HTTP request
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
If I replace the URL, using the encoder, like this:
String url = "https://graph.facebook.com/pageId/feed?access_token=MyAppId" + URLEncoder.encode("|", "UTF-8") + "mySecretKey&limit=10";
I receive the error:
{"error":{"message":"(#200) The user hasn't authorized the application to perform this action","type":"OAuthException","code":200}}
But If I copy and paste the original URL, it's returning successfully the JSON
How can I send correctly the url on this case?

Http post in android with nested associative array

I am trying to send an http post request to a PHP service. Here is an example of how the input may look with some test data
I know that the Java alternative to the PHP associative arrays are HashMaps, but I wonder can this be done with NameValuePairs? What is the best way to format this input and call the PHP service via post request?
Extending #Sash_KP's answer, you can post the nameValuePairs like this too:
params.add(new BasicNameValuePair("Company[name]", "My company"));
params.add(new BasicNameValuePair("User[name]", "My Name"));
Yes this can be done with NameValuePair.You can have something like
List<NameValuePair> params;
//and when making `HttpPost` you can do
HttpPost httpPost = new HttpPost("Yoururl");
httpPost.setEntity(new UrlEncodedFormEntity(params));
//and while building parameters you can do somethin like this
params.add(new BasicNameValuePair("name", "firemanavan"));
params.add(new BasicNameValuePair("cvr", "1245678"));
....
Here's a neat and nice parsing method which you can use.
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
JSONObject jObj = null;
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
And you can simply use it something like
getJSONFromUrl("YourUrl", params);
Now this is just a basic idea of how you can achieve this using NameValuePair.You will have to need some more workaround to implement exactly as you want, but this should provide you the basic idea.Hope this helps.

String from server cannot be converted to JSONObject?

My server returns a JSON object via the body of an HTTP POST response, but I get the this error when my app tries to convert the string into a JSONObject:
06-02 09:05:34.380: E/JSONException_MyAppService(19913): org.json.JSONException: Value {"VALS":{"VAL1":"hello","VAL2":"hello2","VAL3":"hello3"}} of type java.lang.String cannot be converted to JSONObject
It looks like my server is returning a acceptable JSON encoded string, but it just won't convert to a JSONObject. I even changed the content-type of the server's response header to "application/json". Please help me fix this, I've been trying all day.
EDIT- I use the following code:
try {
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = client.execute(post, responseHandler);
JSONObject response=new JSONObject(responseBody);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
I also tried imran khan's suggestion:
try {
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONArray tokenList = result.getJSONArray("VALS");
JSONObject oj = tokenList.getJSONObject(0);
String token = oj.getString("VAL1");
String token1 = oj.getString("VAL2");
String token11 = oj.getString("VAL3");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
:'( :'(
How are you doing it? It should work with:
JSONObject object = new JSONObject (yourString);
You can convert string to json as:
String str="{\"VALS\":{\"VAL1\":\"hello\",\"VAL2\":\"hello2\",\"VAL3\":\"hello3\"}}";
try {
JSONObject result = new JSONObject(str);
JSONObject resultf = result.getJSONObject("VALS");
Toast.makeText(this, resultf.getString("VAL1").toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, resultf.getString("VAL2").toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, resultf.getString("VAL3").toString(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONObject object2 = result.getJSONObject("VALS");
String token = object2.getString("VAL1");
String token = object2.getString("VAL2");
String token = object2.getString("VAL3");
}
}
catch (Exception e) {
}
I FIXED IT! It was entirely my server's fault. It turned out that my server was responding incorrectly. What happened was there was a bug within the web framework and after updating to the latest version, the problem solved itself. I'm guessing the old version of the web framework returned the incorrect content-type response header, or used some weird encoding.
So everyone's Java code here should be 100% correct, because Java was not at fault here. THANKS FOR ALL YOUR EFFORT!
Miguel's answer was the closest explanation, so I will accept his answer.

Categories

Resources