http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews
This is my web service. I want to parse it and I want show news_id and news title. Please post, showing me how to parse it so that I can store all the values in a string. I tried but am getting Exception ..
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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,"UTF-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
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());
}
// String name;
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
json_data = jArray.getJSONObject(i);
// name=json_data.getString("name");
map.put("id", String.valueOf(json_data.getString("news_id")));
map.put("title",json_data.getString("news_title"));
map.put("shortdescription",json_data.getString("news_short_description"));
map.put("date",json_data.getString("news_date"));
mylist.add(map);
}
}
catch(Exception e)
{
}
}
You can parse using Gson parser.
So first download gson-1.1.jar file from http://findjar.com/jar/com/google/code/gson/gson/1.1/gson-1.1.jar.html
and then add jar file into your project build path then use the below code for parsing (Simple replace your parsing code with below code)
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Gson gson = new Gson();
Type collectionType = new TypeToken<List<NewsData>>(){}.getType();
List<NewsData> details = gson.fromJson(data, collectionType);
}
catch (Exception e)
{
Log.i("error","error");
e.printStackTrace();
}
bean for above code is
public class NewsData
{
private String news_id = null;
private String news_title = null;
private String news_short_description = null;
private String news_date = null;
public String getNews_id()
{
return news_id;
}
public void setNews_id(String newsId)
{
news_id = newsId;
}
public String getNews_title()
{
return news_title;
}
public void setNews_title(String newsTitle)
{
news_title = newsTitle;
}
public String getNews_short_description()
{
return news_short_description;
}
public void setNews_short_description(String newsShortDescription)
{
news_short_description = newsShortDescription;
}
public String getNews_date()
{
return news_date;
}
public void setNews_date(String newsDate)
{
news_date = newsDate;
}
}
and add internet permission in your manifest
<uses-permission
android:name="android.permission.INTERNET" />
I hope this will help you.
if you still not get your result you can use below code .
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jsonArray=null;
static String json = "";
mJsonArray=getJSONFromUrl(url);
try{
JSONObject mJsonObject=null;
for(int i =0;i<mJsonArray.length();i++){
if(!mJsonArray.isNull(i)){
HashMap<String, String> map = new HashMap<String, String>();
mJsonObject=mJsonArray.getJSONObject(i);
map.put("title",mJsonObject.getString("news_title"));
map.put("shortdescription",mJsonObject.getString("news_short_description"));
map.put("date",mJsonObject.getString("news_date"));
//add you map in to list
}
}
}catch(JSONException jexc){
jexc.printStackTrace();
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
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 {
jsonArray =new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jsonArray;
}
Related
I want to get the data ["04:44","05:59","12:03","15:29","18:07","18:07","19:17"]
from a server that is secure with login and password.
I already have the code for get the datajson:
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
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;
}
How can I
connect with the server and
how can I get the data from jObj?
I construct the JSON Object
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
I Execute an AsyncTask
new HTTPtoServer().execute(jsonobj);
The AsyncTask looks like this:
private class HTTPtoServer extends AsyncTask<JSONObject, Void, String> {
#Override
protected String doInBackground(JSONObject... params) {
//Prepare HTTP Post Client
DefaultHttpClient myClient = new DefaultHttpClient();
HttpPost myPost = new HttpPost(ElasticBeanStalkEndpoint);
StringEntity se = null;
Log.v("TEST","TEST");
try {
se = new StringEntity(params[0].toString());
Log.v("MY SE", se.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
myPost.setEntity(se);
HttpResponse httpresponse = null;
try {
httpresponse = myClient.execute(myPost);
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(httpresponse.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return responseText;
}
#Override
protected void onPostExecute(String s) {
Log.v("MY STRING", s);
}
}
However my JSON Object appears to never be "sending"?
Or maybe it is, but in an incorrect format?
The Java Tomcat server doesn't seem to be doing anything with the data?
My StringEntity results in :
org.apache.http.entity.StringEntity#528111f8
When I do se.toString()... Is this correct?
I seem to be a bit confused.
SERVER CODE:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
try {
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = new JSONObject(buffer.toString());
PrintWriter out = response.getWriter();
String action = jsonObject.getString("action");
log("action: " + action);
JSONObject requestObject = jsonObject.getJSONObject("request");
log("requestObject: " + requestObject);
if (action.equalsIgnoreCase("put-point")) {
putPoint(requestObject, out);
} else if (action.equalsIgnoreCase("get-point")) {
getPoint(requestObject, out);
} else if (action.equalsIgnoreCase("update-point")) {
updatePoint(requestObject, out);
} else if (action.equalsIgnoreCase("query-rectangle")) {
queryRectangle(requestObject, out);
} else if (action.equalsIgnoreCase("query-radius")) {
queryRadius(requestObject, out);
} else if (action.equalsIgnoreCase("delete-point")) {
deletePoint(requestObject, out);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log(sw.toString());
}
}
private void putPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException {
GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng"));
AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(UUID.randomUUID().toString());
AttributeValue schoolNameKeyAttributeValue = new AttributeValue().withS(requestObject.getString("schoolName"));
PutPointRequest putPointRequest = new PutPointRequest(geoPoint, rangeKeyAttributeValue);
putPointRequest.getPutItemRequest().addItemEntry("schoolName", schoolNameKeyAttributeValue);
PutPointResult putPointResult = geoDataManager.putPoint(putPointRequest);
printPutPointResult(putPointResult, out);
}
Try like that.
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
new SendData().execute(jsonobj.toString());
public class SendData extends AsyncTask<String, Integer, Double>{
String response="";
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
}
public void postData(String jsondata) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",jsondata));
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse res = httpclient.execute(httpPost);
InputStream content = res.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
System.out.println("response from server"+response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
SERVER SIDE-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsondata=request.getParameter("json");
//now parse your data from json
try {
JSONObject JsonObject=new JSONObject(jsondata);
JSONObject object=JsonObject.getJSONObject("request");
String action=object.getString("action");
String lng=object.getString("lng");
String lat=object.getString("lat");
String rangeKey=object.getString("rangeKey");
String schoolName=object.getString("schoolName");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I hope this will help you...!
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PROJECT_ID, params[0]));
nameValuePairs.add(new BasicNameValuePair(BROKER_ID,params[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuilder responseJsonStr = new StringBuilder();
while ((output = br.readLine()) != null) {
responseJsonStr.append(output);
}
String queryString = Utils.getQueryString(nameValuePairs);
System.out.println("Query String "+URL +"&"+queryString);
//System.out.println("response Json String "+responseJsonStr );
if(!StringUtils.startsWith(responseJsonStr.toString(), "[")) {
responseJsonStr.insert(0,"[");
responseJsonStr.append("]");
}
try this:
public String getJson(Context applicationContext,String url) {
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("response_key",PrefernceSettings.getRestKey()));
nameValuePair.add(new BasicNameValuePair("response_request","auto_payments"));
Log.e("",String.valueOf(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
try{
if(is != null){
result = convertInputStreamToString(is);
Log.e("result", result);
}else{
result = "Did not work!";
}
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
public String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
try {
while((line = bufferedReader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Try using this function:
public boolean postJSON(JSONObject jsonobj) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost("YOUR URL HERE");
StringEntity se = new StringEntity(jsonobj.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
//Send Http request
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
String resonseStr = EntityUtils.toString(entity);
return getResponse(resonseStr);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
0D
where getResponse is a function that gets the response string and parses it and returns true or false according to how you define the web service.
I have an application that post data to a php file in an online server. When the post is done i get a garbage of html code. In it says I have a php error and that is Invalid argument supplied for each() on line 33. However this problem does not occur if I run it in localhost. I don't understand why this problem is occuring. So someone please help me to solve it.
The following is my jsonparser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", name.toString()));
for (NameValuePair nvp : postParams) {
String name2 = nvp.getName();
String value = nvp.getValue();
Log.d("NameValue pair content", ""+name2+""+value);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("",responseBody);
}
if (method == "GET") {
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();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
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;
}
}
The following is the php file on the server
<?php
header('Content-type: application/json');
/*define('DB_NAME', 'a1422982_sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');*/
define('DB_NAME', 'onlineshop');
define('DB_USER', 'shop');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'mysql28.000webhost.com');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
//var_dump(json_decode ($_POST['json'])));
if($_POST['json']){
$parsed = json_decode($_POST['json'],TRUE);
$i=0;
foreach ($parsed as $obj) {
$ProductName = $obj['Name'];
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$i++;
echo $ProductName." ".$ProductQuantity;
}
}else{
echo "empty";
}
?>
there's a missing options on your HttpPost request set the entity metadata and the resulting entity as string.
In your java code you can do this:
Map<String, String> postData = new HashMap<String, String>();
postData.put("KEY", "yourvalue");
JSONObject holder = new JSONObject(postData);
StringEntity jsonStringEntity = new StringEntity(holder.toString());
httpost.setEntity(jsonStringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
in that way your PHP code could actually parse your post data since json_decode() expecting json as parameter.
I have developed an application, that has text view for display some Gujarati text from the JSON URL and data stored in PHP MySQL server database.
So, problem with display Gujarati font:
My code of JSON http is here:
public class CustomHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
// in = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8000);
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
and main activity code here:
desc_about=(TextView)v.findViewById(R.id.textdesc);
Typeface tf=Typeface.createFromAsset(getActivity().getAssets(),"Shruti.ttf");
desc_about.setTypeface(tf);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("temple_id","2"));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
url_temple,postParameters);
String result = response.toString();
try {
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
about_temple=json_data.getString("about_text");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
try{
desc_about.setText(about_temple);
}
catch(Exception e){
Log.e("log_tag","Error in Display!" + e.toString());;
Toast.makeText(getActivity(), "error" + 2, 100).show();
}
}
catch (Exception e) {
Log.e("log_tag","Error in http connection!!" + e.toString());
Toast.makeText(getActivity(), "error" + 3, 100).show();
}
Try using utf-endcoding at the time of making JSON on php side and same way decode utf in android side. I solved it using this way in iOS app, Thanks
Try this solution
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://floming.com/shayri/guj_romanse.json", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String str = "";
try {
str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();
Got stuck at this error:
3169-3190/com.meisolsson.app E/JSON Parserīš Error parsing data org.json.JSONException: Value [{"type":0,"can_see_custom_stories":true,"display":"","name":"jenniaim"},{"type":0,"can_see_custom_stories":true,"display":"","name":"lucasgardebrand"},{"type":0,"can_see_custom_stories":true,"display":"","name":"herr_anderzzon"},{"type":0,"can_see_custom_stories":true,"display":"","name":"chrillebile"},{"type":0,"can_see_custom_stories":true,"display":"","name":"meisolsson"},{"type":0,"can_see_custom_stories":true,"display":"","name":"sakanapanda"},{"type":0,"can_see_custom_stories":true,"display":"Team Snapchat","name":"teamsnapchat"},{"type":0,"can_see_custom_stories":true,"display":"","name":"fabianlindfors"},{"type":0,"can_see_custom_stories":true,"display":"Katja","name":"katjaawesome"},{"type":0,"can_see_custom_stories":true,"display":"","name":"swimkey"},{"type":1,"can_see_custom_stories":true,"display":"","name":"agnesholmberg"}] of type org.json.JSONArray cannot be converted to JSONObject
So here is the code:
public class JSONParser extends AsyncTask<Void, Void, Boolean> {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", LoginActivity.Suser));
nameValuePairs.add(new BasicNameValuePair("password", LoginActivity.Spass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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;
}
#Override
protected Boolean doInBackground(Void... params) {
getJSONFromUrl("http://flapplabs.se/development/snapchat/friends.php");
return null;
}
}
[..] means it should be an JSONArray and {..} means it should be a JSONObject.
Therefore:
try {
JSONArray jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Even though I had a single JSON object it was stored in an array as
Hariharan has pointed out with the square brackets [ { items:items, ... } ]
My solution was simply to parse out the only object, located in array position [0] like this
JSONArray jsonArray = new JSONArray(stringIn);
JSONObject obj = jsonArray.getJSONObject(0);