Im trying to get JSONobject from api but i cant get this piece of code to work.
I am new to android and java and JSON. i keep getting the error: in JSONobject cannot be applied
Main code:
try {
APIClientJSONObject api = new APIClientJSONObject();
JSONObject result = null;
try {
result = api.execute(URL).get();
} catch (Exception e) {
e.printStackTrace();
}
List<CustomListView> contents = new ArrayList<CustomListView>();
try {
JSONObject row = result.getJSONObject(result**ERROR HERE**);
String content = row.optString("FormattedName");
String content2 = row.optString("Title");
String content3 = row.optString("Subtitle");
String content4 = row.optString("Text");
EditText name = (EditText) findViewById(R.id.etInternNaam);
name.setText(content);
EditText titel = (EditText) findViewById(R.id.etName);
titel.setText(content2);
EditText ondertitel = (EditText) findViewById(R.id.etOndertitel);
ondertitel.setText(content3);
EditText EditText = (EditText) findViewById(R.id.etTekst);
EditText.setText(Html.fromHtml(content4));
} catch (JSONException e) {
e.printStackTrace();
}
Api client:
public class APIClientJSONObject extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = new JSONObject(builder.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
JSON output:
{
"FormattedName": "Home page | Footer grijs",
"Title": null,
"Subtitle": null,
"Text": "<div style=\"text-align: center;\"><img style=\"max-width: 80%;\" src=\"/MoxieManager/code.PNG\" alt=\"\"></div>",
"WebsiteId": "6869a7a1-0d65-4cfa-9df1-b0b0d346212e",
"Id": "b9906cb0-cdb2-484a-b603-020e8b64f97b",
"DateCreated": "2016-01-25T12:09:50.367",
"DateModified": "2016-02-11T08:51:54.223",
"CreatedBy": "Drie-O Automatisering",
"ModifiedBy": "Drie-O Automatisering",
"SortOrder": 0
}
Reason:
You are already getting the JSONObject from AsycnTask. There is no need of
JSONObject row = result.getJSONObject(result);
When you try to used this it means you are trying to find a object result inside object result. Which is not the case here.
Solution:
You should remove the above mentioned call and use result in these calls like below.
String content = result.optString("FormattedName");
String content2 = result.optString("Title");
String content3 = result.optString("Subtitle");
String content4 = result.optString("Text");
Is the error coming at this line?
JSONObject row = result.getJSONObject(result);
result is a JSONObject, and the method requires a String.
Why not try to convert result to String and pass it. Something like.
JSONObject resultJson = new JSONObject();
result.toString();
JSONObject row = result.getJSONObject(resultJson );
You have already got the JSON output as given from the APIClient.
JSONObject row = result.getJSONObject(result);
this line is redundant unless your real response is an array list enclosed object and you are getting only a row from it.
Directly you can access internal elements in main object now.
Related
I am trying to get JSON data from a JSON array which looks like this:
{
"common": [
{
"food_name": "eggs",
"serving_unit": "large",
"tag_name": "raw eggs",
"serving_qty": 1,
"common_type": null,
"tag_id": "775",
"photo": {
"thumb": "https://d2xdmhkmkbyw75.cloudfront.net/775_thumb.jpg"
},
"locale": "en_US"
},
Here's what I am using:
public class GetDietData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String calories = "UNDEFINED";
try {
URL urlForGetRequest = new URL("https://trackapi.nutritionix.com/v2/search/instant?query=egg");
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("x-app-key", "REMOVED");
connection.addRequestProperty("x-app-id", "REMOVED");
InputStream stream = new BufferedInputStream(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject();
JSONArray common = jsonRes.getJSONArray("common");
for (int i=0; i<common.length(); i++)
{
JSONObject jsonObj = common.getJSONObject(i);
calories = jsonObj.getString("food_name");
}
connection.disconnect();
} catch (IOException | JSONException e) {
editText=(findViewById(R.id.editTextDiet));
e.printStackTrace();
}
return calories;
}
#Override
protected void onPostExecute(String calories) {
if (calories == "UNDEFINED") {
Toast.makeText(Diet.this, "Food not found", Toast.LENGTH_LONG).show();
} else {
editText=(findViewById(R.id.editTextDiet));
editText.setText(calories);
}
}
}
I have the following problem:
W/System.err: org.json.JSONException: No value for common
at org.json.JSONObject.get(JSONObject.java:392)
So the problem seems to be that the "common" array has no value, hence it cannot find it's length? I'm unsure as to why it cannot see the "common" array as i have looked at numerous other questions about getting Objects from Arrays and I have replicated the code identically each time but with the same result. If I use solely a JSONObject and ignore the full array I can see in the stacktrace that it is attempting to download the whole array into that object which means it's definitely not something wrong with the GET request or the API keys.
Thanks.
the error you are getting is because you aren't passing the String response to jsonObject so it can't find any thing in an empty object
the fix is
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject(inputString); \\this is the fix
JSONArray common = jsonRes.getJSONArray("common");
I'm trying to build a very basic weather app in android studio. I am using AsyncClass to return multiple strings.
As you can see in the code, I used a class named "Wrapper" that is used to store my strings so I can just return a class object and use it in the onPostExecute method of the AsyncTask. The problem I am facing is that when I test the app, all of the returned Strings somehow are undefined (the default for the Wrapper class). This means the strings are not being updated in the doInBackground method and I can't seem to figure out why!
My Activity
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}
private class Wrapper
{
String Temperature = "UNDEFINED";
String city = "UNDEFINED";
String country = "UNDEFINED";
}
private class GetWeatherTask extends AsyncTask<String, Void, Wrapper> {
private TextView textView;
public GetWeatherTask(TextView textView) {
this.textView = textView;
}
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
String Temperature = "x";
String city = "y";
String country = "z";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject cityobj = topLevel.getJSONObject("city");
Temperature = String.valueOf(main.getDouble("temp"));
city = cityobj.getString("name");
country = cityobj.getString("country");
w.Temperature= Temperature;
w.city= city;
w.country=country;
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
#Override
protected void onPostExecute(Wrapper w) {
textView.setText("Current Temperature: " + w.Temperature + " C" + (char) 0x00B0
+"\n" + "Current Location: "+ w.country +"\n" + "City: "+ w.city );
}
}
}
UPDATE:
turned out that that I was using the wrong url in my code,I was using :
http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s
Instead I should've been using:
http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=%s&appid=%s
-aka instead of weather I should've been using forcast
Your error starts here
JSONObject main = topLevel.getJSONObject("main");
Probably because the topLevel object has no "main" key.
{
"city":{ },
"cod":"200",
"message":0.1859,
"cnt":40,
"list":[ ]
}
Throw your JSON into here. https://jsonformatter.curiousconcept.com/
You'll notice that there are many, many "main" keys that are within the "list" element, but you have to parse those starting from getJSONArray("list").
Basically, something like this
String city = "undefined";
String country = "undefined";
List<Double> temperatures = new ArrayList<Double>();
try {
JSONObject object = new JSONObject(builder.toString());
JSONObject jCity = object.getJSONObject("city");
city = jCity.getString("name");
country = jCity.getString("country");
JSONArray weatherList = object.getJSONArray("list");
for (int i = 0; i < weatherList.length(); i++) {
JSONObject listObject = weatherList.getJSONObject(i);
double temp = listObject.getJSONObject("main").getDouble("temp");
temperatures.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
return new Wrapper(city, country, temperatures);
After studying your code, either your try block is failing, which is returning your object, but empty, or there is something wrong with your JSON parsing. If you could show us the JSON you are trying to parse that would be a great help.
That being said, the fact that it is still showing as "UNDEFINED" is because that is how you initialised it, and becuase (the JSON parse is likely failing), the object is being returned in an un-edited state.
EDIT:
You are parsing the JSON wrong. You are trying to find an object called "main" in the top directory, however the main object only exists inside of an array called list!
Please look here for a more easy to see and visual representation: http://prntscr.com/dlhlrk
You can use this site to help visualise your JSON and create an appropriate soluton based upon it. https://jsonformatter.curiousconcept.com/
Looking at the API you posted earlier (api.openweathermap.org) you are trying to access variables that don't exist. I suggest you have a look at what the API returns and try getting the variables one by one if you are getting a JSONException
EDIT:
What API you are using? In your initial post you said it was http://api.openweathermap.org/data/2.5/weather but in a comment above you said it was http://api.openweathermap.org/data/2.5/forecast.
If you're using the weather API (as initially stated) you can use the below:
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.d("JSON", builder.toString());
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject sys = topLevel.getJSONObject("sys");
w.Temperature = String.valueOf(main.getDouble("temp"));
w.city = topLevel.getString("name");
w.country = sys.getString("country");
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
I need to display the HttpEntity response values in the listview
Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
Here am getting the response values
try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "testUser#123");
object.put("Password", "testPassword#123");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("url");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
HttpEntity entity = response.getEntity();
String response_value = EntityUtils.toString(entity).toString();
// Log.e(TAG, response_value ); //display the output in logcat
if (entity != null) {
//Convert String to JSON Object
JSONObject result = new JSONObject(response_value);
JSONArray tokenList = result.getJSONArray("Files");
for(int i=0;i<=tokenList.length();i++)
{
JSONObject oj = tokenList.getJSONObject(i);
JSONObject oj1 = (JSONObject) tokenList.getJSONObject(i).get("Borrower");
JSONObject oj2 = (JSONObject) tokenList.getJSONObject(i).get("CoBorrower");
JSONObject oj3 = (JSONObject) tokenList.getJSONObject(i).get("LoanDetails");
JSONObject oj4 = (JSONObject) tokenList.getJSONObject(i).get("PropertyAddress");
String fileid = oj.getString("FileID");
String borrowername = oj1.getString("FirstName");
String coborrowername = oj2.getString("FirstName");
String loannumber = oj3.getString("LoanNumber");
String addrs1 = oj4.getString("Address1");
String city = oj4.getString("City");
Log.e(TAG, fileid + "/" + borrowername + "/"+ coborrowername + "/"+ addrs1 + "/"+ city + "/"+ loannumber );
JSONArray orders = oj.getJSONArray("Orders");
for(int n=0;n<orders.length();n++){
JSONObject oj5 = orders.getJSONObject(n);
String appid = oj5.getString("ApplicationOrderId");
String appid1 = oj5.getString("DueDate");
Log.e(TAG, appid +"/"+ appid1);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
Now am displaying the response value in the log cat but i want to display this values in the List View. If you have any idea please help me, thanks in advance.
Create a model class ! and create a new instance from it and set your values , then pass the instance to your adapter !
See this link to know how create a model class :
http://www.vogella.com/tutorials/AndroidListView/article.html#listadvanced_interactive
I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..
here my MainActivity.java
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;
// panggil class parser
JSONparser parser = new JSONparser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getJSONArray(TAG_ID);
page = json.getJSONArray(TAG_page);
pages = json.getJSONArray(TAG_total_pages);
tot_result = json.getJSONArray(TAG_total_results);
for (int i = 0; i < results.length(); i++) {
JSONObject data = results.getJSONObject(i);
String backdrop = data.getString(TAG_backdrop_path);
String idd = data.getString(TAG_id).toString();
String ori = data.getString(TAG_original_title);
String releas = data.getString(TAG_release_date);
String poster = data.getString(TAG_poster_path);
String title = data.getString(TAG_title);
String average = data.getString(TAG_vote_average);
String count = data.getString(TAG_vote_count);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_backdrop_path, backdrop);
map.put(TAG_ID, idd);
map.put(TAG_original_title, ori);
map.put(TAG_release_date, releas);
map.put(TAG_poster_path, poster);
map.put(TAG_title, title);
map.put(TAG_vote_average, average);
map.put(TAG_vote_count, count);
genreList.add(map);
}
// Sort by
/*********************************
* Collections.sort(genreList, new Comparator<HashMap<String,
* String>>() {
*
* #Override public int compare(HashMap<String, String> a,
* HashMap<String, String> b) { return
* a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
******************************/
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
// tampilkan ke listadapter
ListAdapter adapter = new SimpleAdapter(this, genreList,
R.layout.list_data, new String[] { TAG_ID, TAG_page,
TAG_results, TAG_backdrop_path, TAG_id,
TAG_original_title, TAG_release_date, TAG_poster_path,
TAG_title, TAG_vote_average, TAG_vote_count,
TAG_total_pages, TAG_total_results }, new int[] {
R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
R.id.idd, R.id.original_title, R.id.release_date,
R.id.poster_path, R.id.title, R.id.vote_average,
R.id.vote_count, R.id.total_pages, R.id.total_results });
setListAdapter(adapter);
}
}
here my JSONparser.java
public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONparser() {
}
public JSONObject getJSONFromUrl(String url) {
// http request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 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) {
// TODO: handle exception
Log.e("BUffer Error", "Error converting result" + e.toString());
}
// try parse string to a json
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO: handle exception
Log.e("Json parser", "error parsing data" + e.toString());
}
return jObj;
}
}
here my json data.
{
"id": 18,
"page": 1,
"results": [
{
"backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
"id": 238,
"original_title": "The Godfather",
"release_date": "1972-03-24",
"poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
"title": "The Godfather",
"vote_average": 9.1999999999999993,
"vote_count": 125
},
{
"backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
"id": 857,
"original_title": "Saving Private Ryan",
"release_date": "1998-07-24",
"poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
"title": "Saving Private Ryan",
"vote_average": 8.9000000000000004,
"vote_count": 83
}
],
"total_pages": 25,
"total_results": 499
}
JSONObject jObject_Main= new JSONObject(jsonstring);
//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");
//get json Array and parse it.
JSONArray jsonArray = jObject_Main
.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");
}
i hope its useful to you.
please change this in your code:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString("id");
page = json.getString("page");
tot_result = json.getJSONArray(results);
i hope you understand it.
Try this..
In your Global:
JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;
Inside Try Catch:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString(TAG_ID); // Changes here
page = json.getString(TAG_page); // Changes here
pages = json.getString(TAG_total_pages); // Changes here
tot_result = json.getString(TAG_total_results); // Changes here
results = json.getJSONArray(TAG_results); // Add this line
for (int i = 0; i < results.length(); i++) {
// Remaining all correct
}
EDIT:
new DownloadImageTask()
.execute("your image url");
}
and DownloadImageTask.class
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}
Your JSON is JSONObject and it contains JSONArray
Parse Object
Parse Array
Example:
JSONObject jsonObj = new JSONObject(your_json_string);
String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");
JSONArray results = jsonObj.getJSONArray("results");
int len = results.length(); // length or size, I don't remember, you can check it
for (int i = 0; i < len; i++) {
JSONObject obj = results.getJSONObject(i);
String backdropPath = obj.getString("backdrop_path");
// ...
}
you need add " results= json.getJSONArray(TAG_results);" below
"tot_result = json.getJSONArray(TAG_total_results);"
I want to communicate with a web server and exchange JSON information.
my webservice URL looking like following format: http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus
Here is my JSON Request format.
{
"f": {
"Adults": 1,
"CabinClass": 0,
"ChildAge": [
7
],
"Children": 1,
"CustomerId": 0,
"CustomerType": 0,
"CustomerUserId": 81,
"DepartureDate": "/Date(1358965800000+0530)/",
"DepartureDateGap": 0,
"Infants": 1,
"IsPackageUpsell": false,
"JourneyType": 2,
"PreferredCurrency": "INR",
"ReturnDate": "/Date(1359138600000+0530)/",
"ReturnDateGap": 0,
"SearchOption": 1
},
"fsc": "0"
}
I tried with the following code to send a request:
public class Fdetails {
private String Adults = "1";
private String CabinClass = "0";
private String[] ChildAge = { "7" };
private String Children = "1";
private String CustomerId = "0";
private String CustomerType = "0";
private String CustomerUserId = "0";
private Date DepartureDate = new Date();
private String DepartureDateGap = "0";
private String Infants = "1";
private String IsPackageUpsell = "false";
private String JourneyType = "1";
private String PreferredCurrency = "MYR";
private String ReturnDate = "";
private String ReturnDateGap = "0";
private String SearchOption = "1";
}
public class Fpack {
private Fdetails f = new Fdetails();
private String fsc = "0";
}
Then using Gson I create the JSON object like:
public static String getJSONString(String url) {
String jsonResponse = null;
String jsonReq = null;
Fpack fReq = new Fpack();
try {
Gson gson = new Gson();
jsonReq = gson.toJson(fReq);
JSONObject json = new JSONObject(jsonReq);
JSONObject jsonObjRecv = HttpClient.SendHttpPost(url, json);
jsonResponse = jsonObjRecv.toString();
}
catch (JSONException e) {
e.printStackTrace();
}
return jsonResponse;
}
and my HttpClient.SendHttpPost method is
public static JSONObject SendHttpPost(String URL, JSONObject json) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(json.toString());
httpPostRequest.setEntity(se);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
return jsonObjRecv;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Now I get the following exception:
org.json.JSONException: Value !DOCTYPE of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)
and the printout of JSON string right before I make the request is as follows:
{
"f": {
"PreferredCurrency": "MYR",
"ReturnDate": "",
"ChildAge": [
7
],
"DepartureDate": "Mar 2, 2013 1:17:06 PM",
"CustomerUserId": 0,
"CustomerType": 0,
"CustomerId": 0,
"Children": 1,
"DepartureDateGap": 0,
"Infants": 1,
"IsPackageUpsell": false,
"JourneyType": 1,
"CabinClass": 0,
"Adults": 1,
"ReturnDateGap": 0,
"SearchOption": 1
},
"fsc": "0"
}
How do I solve this exception? Thanks in advance!
To create a request with JSON object attached to it what you should do is the following:
public static String sendComment (String commentString, int taskId, String sessionId, int displayType, String url) throws Exception
{
Map<String, Object> jsonValues = new HashMap<String, Object>();
jsonValues.put("sessionID", sessionId);
jsonValues.put("NewTaskComment", commentString);
jsonValues.put("TaskID" , taskId);
jsonValues.put("DisplayType" , displayType);
JSONObject json = new JSONObject(jsonValues);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url + SEND_COMMENT_ACTION);
AbstractHttpEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
return getContent(response);
}
I'm not quite familiar with Json, but I know it's pretty commonly used today, and your code seems no problem.
How to convert this JSON string to JSON object?
Well, you almost get there, just send the JSON string to your server, and use Gson again in your server:
Gson gson = new Gson();
Fpack f = gson.fromJSON(json, Fpack.class);
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html
About the Exception:
You should remove this line, because you are sending a request, not responsing to one:
httpPostRequest.setHeader("Accept", "application/json");
And I would change this line:
httpPostRequest.setHeader("Content-type", "application/json");
to
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
If this doesn't make any difference, please print out your JSON string before you send the request, let's see what's in there.
From what I have understood you want to make a request to the server using the JSON you have created, you can do something like this:
URL url;
HttpURLConnection connection = null;
String urlParameters ="json="+ jsonSend;
try {
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
Actually it was a BAD REQUEST. Thats why server returns response as XML format.
The problem is to convert the non primitive data(DATE) to JSON object.. so it would be Bad Request..
I solved myself to understand the GSON adapters.. Here is the code I used:
try {
JsonSerializer<Date> ser = new JsonSerializer<Date>() {
#Override
public JsonElement serialize(Date src, Type typeOfSrc,
JsonSerializationContext comtext) {
return src == null ? null : new JsonPrimitive("/Date("+src.getTime()+"+05300)/");
}
};
JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
#Override
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext jsonContext) throws JsonParseException {
String tmpDate = json.getAsString();
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(tmpDate);
boolean found = false;
while (matcher.find() && !found) {
found = true;
tmpDate = matcher.group();
}
return json == null ? null : new Date(Long.parseLong(tmpDate));
}
};