I'm new to JSON android java eclipse. I am doing a listview with images and parsing json array. I followed this tutorial: http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ . In that tutorial, their JSON array contains the array name.However, mine doesn't contain the array name. So my question is how to code JSON Array without the array name?
Below is my JSON code.
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
},
{
"event_id": "EV00000002",
"event_title": "Movie2",
}
]
Below is my JSON coding for parsing the JSON.
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Events event = new Events();
event.setevent_title(object.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
What am i suppose to do?
This problem is solved. Thus, i will be posting the correct code.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Events event = new Events();
event.setevent_title(obj.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
Here is a little example:
JSONArray array = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("key", "value");
array.put(obj1);
JSONObject obj2 = new JSONObject();
obj2.put("key2", "value2");
array.put(obj2);
That would look like:
[
{
"key": "value"
},
{
"key2": "value2"
}
]
If you want to get information about your JSONObjects in your JSONArray just iterate over them:
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
object.get("event_id");
object.get("event_title");
}
You can use GSON librery, it's very easy to use. Just create a class (model)
public class Event{
private String event_id;
private String event_title;
...
}
and in your main activity
Event ev = new Event ("EV00000001", "Movie 1")
Gson gson = new Gson();
gSon = gson.toJson(ev);
Log.i("gson", gSon);
and you will get JSON
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
}
]
What you have is an array of JSON Objects.
What the tutorial has is a JSON Object that has a property, which has an array of JSON objects.
When you look at these, here is a simple way to differentiate the two:
[] -> Array
{} -> Object
So in your code, instead of doing
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
You might want to do:
JSONArray jarray = new JSONArray(data);
Related
I want to post data to the url and getting Null pointer exception
My JSON URL contains
{
"Details":
[
{
"Status":"NO UPDATES"
}
]
}
I'm getting the error the line:
String status = object.getString("Status").trim(); //error Line
Full code:
btnPost = (Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
btnPost.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("null")
#Override
public void onClick(View arg0)
{
try
{
String postReceiverUrl = "http://";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
#SuppressWarnings("resource")
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
jsonobject.put("IDNo", IDNo.getText().toString());
jsonobject.put("Position", Position.getText().toString());
jsonobject.put("Data", Data.getText().toString());
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
Log.v("jsonResult",jsonResult);
JSONObject object = new JSONObject(jsonResult);
String status = object.getString("Status").trim();
Toast.makeText(getBaseContext(), "Please wait...",100).show();
if(status.toString().equals("SUCCESS"))
{
Intent i = new Intent(LoginPage.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
if(status.toString().equals("FAILED"))
{
Toast.makeText(getBaseContext(), "Wrong Credentials",100).show();
}
else
{
Toast.makeText(getBaseContext(), "Details Inserted",100).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
Do proper parsing of the JSON as , you see yours response:-
{ "Details":[{"Status":"NO UPDATES"}]}
So Firstly try to make the object of the JSONObject than after the JSONArray , look at below example:-
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray detailsArray = jsonObject.getJSONArray("Details");
String status = dataArray.getJSONObject(0).getString("status");
Toast.makeText(getBaseContext(), "Please wait...",100+status).show();
your code should be like this
JSONObject object = new JSONObject(jsonResult);
JSONOArray details = object.getJSONArray("Details");
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String status = c.getString("Status");
}
Toast.makeText(getBaseContext(), "Please wait...",100).show();
Modift String status = object.getString("Status").trim(); to
String status = object.get("Details").getAsJsonArray()[0].getString("Status").trim();
You are using getString("Status") which may return null if key is not available in JSON. I'd suggest you to use optString("Status") it'll return blank String if key is not available.
JSONObject jsonObject = new JSONObject(stringJSON);
JSONArray jsonArray = jsonObject.optJSONArray("Details");
if(jsonArray != null){
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jObject = jsonArray.optJSONObject(i);
if(jObject != null){
String strStatus = jObject.optString("Status");
}
}
}
Try this code
JSONObject object = new JSONObject(jsonResult);
JSONArray array=object.getJsonarray("Details");
for(int i=0;i<array.length();i++)
{
JSONObject innerObject=array.getJsonObject(i);
String s= innerObject.getString("Status");
}
If at any point in your code, org.json.JSONObject json_object becomes null and you wish to avoid NullPointerException (java.lang.NullPointerException), then simply check as following:
if(json_object == null) {
System.out.println("json_object is found as null");
}
else {
System.out.println("json_object is found as not null");
}
Here is a link: http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js with JSON objects. There are 261 objects with unique value (strings). How to get each object with numbers (2101, 2107 etc.) and 2 strings inside (picture and title)?
So this is my technologies AsyncTask:
ListView listView;
TechnologiesAdapter adapter;
ArrayList<Technologies> techList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView);
techList = new ArrayList<Technologies>();
new TechnologiesAsyncTask().execute("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
}
public class TechnologiesAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
//How to get the other objects?
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
You can get all of the names to a json array, then get every json object from the names in json array.
Following is a simple example.
private class DataAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("technology");
JSONArray nameArray = jsonObject.names();
final int size = nameArray.length();
for (int i = 0; i < size; i++) {
JSONObject object = jsonObject.getJSONObject(nameArray.getString(i));
// get id, title and pictures, etc
Log.d(TAG, nameArray.getString(i) + " " + object.getString("title") + " " + object.getString("picture"));
}
} catch (IOException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
After you get the "technology" object just create another JSONObject from that like this:
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
// Get the 2101 object
JSONObject jObj3 = jObj2.getJSONObject("2101");
// Get the picture and title of 2101
String picture = jObj3.getString("picture");
String title = jObj3.getString("title");
Your JSON looks like it might be better suited to use a JSONArray instead of nested JSONObjects though.
JSONObject jPages=jQuery.getJSONObject("pages");
Iterator < String> keys = jPages.keys();
while(keys.hasNext()){
JSONObject jPageId=jPages.getJSONObject(keys.next());
//Action need to be performed
}
I am trying to parse data from JSON but my JSON data is an array without a string name. Here is an example:
[
{
"$id": "1",
"ClubVideoId": 1027,
"ClubId": 1,
"Title": "Brian Interview",
"ThumbURL": "url",
"VideoURL": "urll",
"DateAdded": "2014-03-25 00:00"
},
{
"$id": "2",
"ClubVideoId": 1028,
"ClubId": 1,
"Title": "Chase Interview",
"ThumbURL": "url",
"VideoURL": "urll",
"DateAdded": "2014-03-25 00:00"
},
I can seem to pass an Array without a string. Here is my code:
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if (mVideoData == null) {
updateDisplayForError();
}
else {
try {
JSONArray jsonPosts = mVideoData.getJSONArray("");
ArrayList<HashMap<String, String>> clubVideos =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
String thumburl = post.getString(KEY_THUMBURL);
thumburl = Html.fromHtml(thumburl).toString();
String dateurl = post.getString(KEY_DATEADDED);
dateurl = Html.fromHtml(dateurl).toString();
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_THUMBURL, thumburl);
blogPost.put(KEY_DATEADDED, dateurl);
clubVideos.add(blogPost);
}
String[] keys = {KEY_THUMBURL, KEY_DATEADDED};
int[] ids = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, clubVideos,
android.R.layout.simple_list_item_2, keys, ids);
setListAdapter(adapter);
} catch (JSONException e) {
Log.e(TAG, "Exception caught!!", e);
}
}
}
Any Suggestions?
Here is where I'm pulling my json:
#Override
protected JSONObject doInBackground(Object... arg0) {
int responseCode = -1;
JSONObject jsonResponse = null;
try {
URL blogFeedUrl = new URL("http://x.com/api/Club/Getx/1/?count=" + NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONObject(responseData);
}
else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
Log.i(TAG, "Code: " + responseCode);
}
catch (MalformedURLException e) {
logException(e);
}
catch (IOException e) {
logException(e);
}
catch (Exception e) {
logException(e);
}
return jsonResponse;
}'
how do I loop through a jsonarray?
JSONArray jr = new JSONArray("json string");
for(int i=0;i<jr.length();i++)
{
JSONObject jb = (JSONObject) jr.get(i);
String id =jb.getString("$id");
String clubvid = jb.getString("ClubVideoId");
...// similarly others
}
As squonk suggested
[ // json array node
{ // json object node
"$id": "1",
Edit:
The below should be in a thread
#Override
protected String doInBackground(Object... arg0)
{
String _response=null;
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://sql.gamedayxtra.com/api/Club/GetClubVideos/1");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
}catch(Exception e)
{
e.printStackTrace();
}
return _response;
}
In onPostExecute
#Override
protected void onPostExecute(String _response)
JSONArray jr = new JSONArray("_response");
for(int i=0;i<jr.length();i++)
{
JSONObject jb = (JSONObject) jr.get(i);
String id =jb.getString("$id");
String clubvid = jb.getString("ClubVideoId");
...// similarly others
}
I am working with webservice in an android app. I could not parse the following response in app. it always gives the
org.json.JSONException: Value
[{"METER_READING":"15","UTILITY_PLAN":"1","uname":"vinayak#triffort.com","kwh_usage":"3","meter_reading_date":"02-13-2014","ESID":"abc","METER_ID":"abc100"}]
at data of type java.lang.String cannot be converted to JSONArray.
Below is my code:
StringEntity entity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response from webservice
{"data":"[{\"METER_READING\":\"25\",\"UTILITY_PLAN\":\"1\",\"uname\":\"vinayak#triffort.com\",\"kwh_usage\":\"9\",\"meter_reading_date\":\"02-13-2014\",\"ESID\":\"abc\",\"METER_ID\":\"abc100\"}]"}
try using something like:
jsonResultStr = jsonResultStr.replace( "\\", "" ).replaceAll( "\"\\[", "[" ).replaceAll( "\\]\"", "]" );
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response
{
"data":"[{\"METER_READING\":\"25...}]"
}
The value of data is not an array; it is a string. That string is valid JSON which you could parse but why the service would do this is unclear.
So this should work:
JSONObject jObject = new JSONObject(jsonResultStr);
String parseMeAgain = jObject.optString("data");
try this simple code:
JSONObject o = new JSONObject(new JSONTokener(postResponse));
JSONArray ja = o.getJSONArray("data");
EDIT
Thanks #McDowell for observation
new JSONArray(new JSONTokener(jObject.optString("data")));
You can do this way :
JSONArray jsonArray = new JSONArray(result); // Pass your result here..
JSONObject jsonObject = jsonArray.getJSONObject(0);
String meterReading = jsonObject.getString("METER_READING");
String plan = jsonObject.getInt("UTILITY_PLAN");
String uname= jsonObject.getString("uname");
String meter_reading_date= jsonObject.getString("meter_reading_date");
String ESID= jsonObject.getString("ESID");
String METER_ID= jsonObject.getString("METER_ID");
Your json should be like this
{
"myarray": [
{
"METER_READING": "15",
"UTILITY_PLAN": "1",
"uname": "vinayak#triffort.com",
"kwh_usage": "3",
"meter_reading_date": "02-13-2014",
"ESID": "abc",
"METER_ID": "abc100"
}
]
}
for network call
public String initializeConnection(String url) {
String result = null;
JSONObject jObj;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if(client==null){Log.i("Clinet **************** ", "Client is null");}
//post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse res = client.execute(post);
result = inputStreamToString(res.getEntity().getContent()).toString();
Log.d("Result from server:", result);
jObj = new JSONObject(result.trim());
} catch (JSONException e1) {
Log.e("Json Exception", e1.toString());
} catch (ClientProtocolException e2) {
Log.e("Client Protocol", e2.toString());
} catch (IOException e3) {
Log.e("Io exception", e3.toString());
}
return result;
}
private StringBuilder inputStreamToString(InputStream is) throws UnsupportedEncodingException {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
to retrive from the json
ArrayList<String> params = new ArrayList<String>();
String result = networkCall.initializeConnection(url);
jObj = new JSONObject(result);
JSONArray jArray = jObj.optJSONArray("myarray");
params.add(jArray.optString(1));
params.add(jArray.optString(2));
params.add(jArray.optString(3));
params.add(jArray.optString(4));
params.add(jArray.optString(5));
params.add(jArray.optString(6));
now the data is stored in the params you can differentiate & store it as you want
I want to get a JSON object from a Http get response:
Here is my current code for the Http get:
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
HttpResponse response;
String result = null;
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
System.out.println("RESPONSE: " + result);
instream.close();
if (response.getStatusLine().getStatusCode() == 200) {
netState.setLogginDone(true);
}
}
// Headers
org.apache.http.Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}
Here is the convertSteamToString function:
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Right now I am just getting a string object. How can I get a JSON object back.
The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.
If you are supposed to get a JSON Object you can just put:
JSONObject myObject = new JSONObject(result);
Do this to get the JSON
String json = EntityUtils.toString(response.getEntity());
More details here : get json from HttpResponse
This is not the exact answer for your question, but this may help you
public class JsonParser {
private static DefaultHttpClient httpClient = ConnectionManager.getClient();
public static List<Club> getNearestClubs(double lat, double lon) {
// YOUR URL GOES HERE
String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);
List<Club> ret = new ArrayList<Club>();
HttpResponse response = null;
HttpGet getMethod = new HttpGet(getUrl);
try {
response = httpClient.execute(getMethod);
// CONVERT RESPONSE TO STRING
String result = EntityUtils.toString(response.getEntity());
// CONVERT RESPONSE STRING TO JSON ARRAY
JSONArray ja = new JSONArray(result);
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
// RETRIEVE EACH JSON OBJECT'S FIELDS
long id = jo.getLong("id");
String name = jo.getString("name");
String address = jo.getString("address");
String country = jo.getString("country");
String zip = jo.getString("zip");
double clat = jo.getDouble("lat");
double clon = jo.getDouble("lon");
String url = jo.getString("url");
String number = jo.getString("number");
// CONVERT DATA FIELDS TO CLUB OBJECT
Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
ret.add(c);
}
} catch (Exception e) {
e.printStackTrace();
}
// RETURN LIST OF CLUBS
return ret;
}
}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:
JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");
Without a look at your exact JSON output, it's hard to give you some working code. This tutorial is very useful, but you could use something along the lines of:
JSONObject jsonObj = new JSONObject("yourJsonString");
Then you can retrieve from this json object using:
String value = jsonObj.getString("yourKey");
For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :
If you want a JSONObject, then first get a String from the result:
String jsonString = EntityUtils.toString(response.getEntity());
Then you can get your JSONObject:
JSONObject jsonObject = new JSONObject(jsonString);
You need to use JSONObject like below:
String mJsonString = downloadFileFromInternet(urls[0]);
JSONObject jObject = null;
try {
jObject = new JSONObject(mJsonString);
}
catch (JSONException e) {
e.printStackTrace();
return false;
}
...
private String downloadFileFromInternet(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
new IllegalArgumentException("url is empty/null");
StringBuilder sb = new StringBuilder();
InputStream inStream = null;
try
{
url = urlEncode(url);
URL link = new URL(url);
inStream = link.openStream();
int i;
int total = 0;
byte[] buffer = new byte[8 * 1024];
while((i=inStream.read(buffer)) != -1)
{
if(total >= (1024 * 1024))
{
return "";
}
total += i;
sb.append(new String(buffer,0,i));
}
}
catch(Exception e )
{
e.printStackTrace();
return null;
}catch(OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
private String urlEncode(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
return null;
url = url.replace("[","");
url = url.replace("]","");
url = url.replaceAll(" ","%20");
return url;
}
Hope this helps you..
There is a JSONObject constructor to turn a String into a JSONObject:
http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
If your api is response is a java object, then the string that you got from Outputstream should be in json string format such as
{\"name\":\"xyz\", \"age\":21}
. This can be converted to JSON object in many ways, out of which one way is to use google GSON library.
GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); Gson gson = builder.create(); <javaobject> = gson.fromJson(<outputString>, <Classofobject>.class);
One can do it without Gson also, using Jackson, which implements Json Tree Model.
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(responseString);
1)String jsonString = EntityUtils.toString(response.getEntity());
2)JSONObject jsonObject = new JSONObject(jsonString);