JSON: issue in parsing json data at server - java

When i passing json data from Android to server , its howing following error at server at the time of parsing.org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
The servlet code is :
protected void doProcess(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
BufferedReader br = request.getReader();
String sCurrentLine;
StringBuilder sb = new StringBuilder();
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
System.out.println(sb.toString().substring(4));
try {
JSONArray jArray = new JSONArray(sb.toString().substring(4));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
json_data.getString("dwsList");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Android portion is :
ArrayList<STRModel> strlist = StrDbHelper
.getPendingStrlist(Splash.this);
System.out.println("--------Inside------" + strlist.size());
if (strlist != null) {
String URL = "http://ip:8080/Admin/upload";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("str", new Gson()
.toJson(strlist)));
System.out.println(new Gson().toJson(strlist));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("Response", response.getEntity().getContent()
.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
I'm passing from client as :
[
{"dwsList":
[
{"farmer_name":"JINJU","dws_date":"2013-03-08","farmer_code":"10004","dws_num":"53","dws_id":4,"bag_weight":3000.0,"net_weight":2000.0,"selected":false,"str_id":0,"totalBags":20},
{"farmer_name":"KANNAN","dws_date":"2013-03-08","farmer_code":"10005","dws_num":"54","dws_id":5,"bag_weight":1500.0,"net_weight":1000.0,"selected":false,"str_id":0,"totalBags":10}
],
"str_total_weight":4000.0,"str_date":"2013-03-08","str_number":"1003","str_id":4,"str_total_bag":0,"status":0,"selected":false}
]
when i print Json data in server its look like
str=%5B%7B%22dwsList%22%3A%5B%7B%22farmer_name%22%3A%22JINJU%22%2C%22dws_date%22%3A%222013-03-08%22%2C%22farmer_code%22%3A%2210004%22%2C%22dws_num%22%3A%2253%22%2C%22dws_id%22%3A4%2C%22bag_weight%22%3A3000.0%2C%22net_weight%22%3A2000.0%2C%22selected%22%3Afalse%2C%22str_id%22%3A0%2C%22totalBags%22%3A20%7D%2C%7B%22farmer_name%22%3A%22KANNAN%22%2C%22dws_date%22%3A%222013-03-08%22%2C%22farmer_code%22%3A%2210005%22%2C%22dws_num%22%3A%2254%22%2C%22dws_id%22%3A5%2C%22bag_weight%22%3A1500.0%2C%22net_weight%22%3A1000.0%2C%22selected%22%3Afalse%2C%22str_id%22%3A0%2C%22totalBags%22%3A10%7D%5D%2C%22str_total_weight%22%3A4000.0%2C%22str_date%22%3A%222013-03-08%22%2C%22str_number%22%3A%221003%22%2C%22str_id%22%3A4%2C%22str_total_bag%22%3A0%2C%22status%22%3A0%2C%22selected%22%3Afalse%7D%5D

You can try below code for parsing JSON
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea, Republic of"},
{"countryCode":"us","countryName":"United States"},
{"countryCode":"jp","countryName":"Japan"},
{"countryCode":"cn","countryName":"China"},
{"countryCode":"in","countryName":"India"}
]
}
public static ArrayList<Country> ParseJson(String jsonstring) {
ArrayList<Country> arrCountries = new ArrayList<Country>();
String status;
String message = "";
try {
JSONObject json = new JSONObject(jsonstring);
status = json.getString("result");
if (status.equalsIgnoreCase("success")) {
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
}
} catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
return arrCountries;
}

Related

Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject in android?

I am trying to access a json array from android. But it shows an exception. This is my android code used for retrieving the json array:
protected void showList(){
final String TAG_RESULTS="result";
final String TAG_USERNAME="username";
final String TAG_NAME = "message_recd";
final String TAG_ADD ="message_sent";
ArrayList<HashMap<String, String>> personList;
personList = new ArrayList<HashMap<String,String>>();
//for tesitng
JSONObject jObject=null;
//
try {
//for testing
//
JSONObject json = new JSONObject(myJSON);
JSONArray peoples =json.getJSONArray("emparray");
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
name = c.getString("user_id");
address = c.getString("crtloc_lat");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("user_id",name);
persons.put("crtloc_lat",address);
personList.add(persons);
Toast.makeText(MapsActivity.this, "woow id"+name, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("errore",e.toString());
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("username", fName));
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abh.netai.net/abhfiles/searchProfession.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
php file
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=0;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($con);
?>
and the json array
[[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769566","crtloc_lng":"72.361031"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]
the error it show me is this
Value [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769749","crtloc_lng":"72.361168"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}] of type org.json.JSONArray cannot be converted to JSONObject
It is giving you this error because the first object in the array is not a JSONObject but an JSONArray following 4 JSONObjects.
[
[],
{
"user_id": "77",
"crtloc_lat": "34.769638",
"crtloc_lng": "72.361145"
},]
As you can see you expect it to always be a JSONObject.
JSONObject c = peoples.getJSONObject(i);
Anticipate on that first JSONArray in the list.

Is this correct approach to submitting JSON via HTTP POST to a java Web Server?

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.

JSON parsing issue with Gujarati font in Android text view

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();

Grabbing JSON content with Java

Here is a sample of my json_encode in PHP:
print(json_encode($row));
leads to {"AverageRating":"4.3"} which is good.
But in Java, I can not seem to grab this 4.3 value. Here it is (for an Android project) I have edited non-relevant data.
public class Rate extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
String Item, Ratings, Review, starAvg;
RatingBar ratingsBar;
ArrayList<NameValuePair> param;
public void onCreate(Bundle savedInstanceState) {
starAvg = "0"; // Sets to 0 in case there are no ratings yet.
new starRatingTask().execute();
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
class starRatingTask extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/average_stars.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", Item));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String starAvgTwo = null;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
starAvg = json_data.getString("AverageRating");
starAvgTwo = starAvg;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Star Ratings!",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
Toast.makeText(getBaseContext(), starAvgTwo,
Toast.LENGTH_LONG).show();
ratingsBar.setRating(Float.valueOf(starAvg));
}
}
That second toast produces a blank (I assume a "" - empty string?). If I change the toast variable back to starAvg, then it toasts "0".
How can I retrieve the value of 4.3.
As we discussed in the comments on the original question, the PHP is sending down as single JSONObject rather than an array. Parsing as a JSONObject is required in it's present state; however, if you begin sending down an array of your value objects, then you'd use JSONArray to parse it.
I think your JSON doesn't contain array. so just do this:
JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable
and try toast the averageRating.
and how to get the array from JSON object?
if you have JSON:
{"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }]
}
then use this code
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}
that code will produce
John Anna Peter
in your LogCat

Json Parsin in android

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;
}

Categories