I am trying to extract data from Json string which is obtained by a response using only Java code.
I am posting my Java code here.
OUTPUT:
Entering into while loop
[{"name":"Frank","food":"pizza","quantity":3}]
This is my Java code.
public void receive()
{
System.out.println("Entering into sendNote method");
try {
// make json string,
String json = "{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}";
// send as http get request
URL url1 = new URL("http://myurl/file.php?usersJSON="+userList);
URLConnection conn1= url1.openConnection();
//I am receiving exactly what I have sent....
BufferedReader rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
{
System.out.println("Entering into while loop");
System.out.println(line);// line contains the received json parameters
//I want to enter the recieved parameters into my database
//
//
//
//I need the solution right here....
}
rd.close();
}
catch (Exception e)
{
System.out.println("Error Occured while receiving");
e.printStackTrace();
}
}
Thank you !!!!!
#Ankur:
This is how I tried,
# Lahiru Prasanna, #ankur-singhal
Thanks a lot.!!
I think that you successfully got HttpResponse.here variable called response is HttpResponse.
// Could do something better with response.
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
content.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(builder.toString());
} catch (JSONException e) {
System.out.println("Error parsing data " + e.toString());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
System.out.println( "" + e.toString());
System.out.println("" + e.toString());
}
And important thing is never use Strings for json operations.
you can retrieve your data from jsonObject like this
String name = jsonObject.getString("name");
There are few ways to achive the same.
1.) Create a response pojo
MyResponse ob = new ObjectMapper().readValue(jsonString, MyResponse.class);
// then call getters on above.
2.) Get key/values
JSONObject json = (JSONObject)new JSONParser().parse(""name":"Frank","food":"pizza","quantity":3}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("food"));
3.) Converting Json to HashMap
public static void main(String[] args) {
try {
jsonToMap("{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}");
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : " + jObject);
System.out.println("map : " + map);
}
output
json : {"name":"Frank","food":"pizza","quantity":3}
map : {food=pizza, name=Frank, quantity=3}
Related
Im trying to parse JSON and my code is not working with one URL and it works with other. I think its the coma in question but I did not sure so please look at my code and help.
I tried to replace coma with dot in loop, but what i get is JSON Exception. And when I change the URL, there is no exception. Confusing...
This is not working URL: http://api.hnb.hr/tecajn/v1
And this is one I tested and it works: https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=e402c76fc8584a1c81849179f1277a74
While changed the URL I also changed the data, so its not the problem in writing..I guess
Here is my code for coma replacement:
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
String coma = line.replaceFirst(",",".");
sb.append(coma).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
And the other part with URL and JSONArray:
#Override
protected Void doInBackground(Void... arg0) {
URLconnection urlConn = new URLconnection();
// Making a request to url and getting response
String url = "http://api.hnb.hr/tecajn/v1";
//.........connection.........
String response = urlConn.makeServiceCall(url);
Log.e(TAG, "Response from url: " + response);
if (response != null) {
try {
JSONObject jsonObj = new JSONObject(response);
// Getting JSON Array node
arr = jsonObj.getJSONArray("values");
for (int i = 0; i < article.length(); i++) {
JSONObject c = arr.getJSONObject(i);
header = c.getString("Valuta");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: 216",
Toast.LENGTH_LONG).show();
}
});
}
Commas aren't the issue. It's the very first character. One is a square bracket and the other is a curly one.
You therefore need to parse the first response as an Array rather than an Object
new JSONArray(response);
That being said, you therefore cannot use the same methods for both URLs
By use of this i'm getting response code and trying to convert String to JSONObject but getting exception.
public JSONObject getJSONFromUrl(String url,List<NameValuePair> nameValuePairsList) {
// Making HTTP request
try {
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 20000);
HttpConnectionParams.setSoTimeout(param, 20000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsList));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PropertyLogger.debug("URL Request: ", url.toString());
PropertyLogger.debug("Encoded Params: ", nameValuePairsList.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
PropertyLogger.debug("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
PropertyLogger.error("UnSupported Exception", e.toString());
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
String TAG = "PropertyJsonParser";
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();
jsonResp = sb.toString();
PropertyLogger.debug("Content: ", sb.toString());
} catch (Exception e) {
PropertyLogger.error("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
PropertyLogger.error("JSON Parser", "Error parsing data :" + e.toString());
return null;
}
return jObj;
}
You get this error because you are not receiving proper JSON response.
Check your api response and possible also provide your api response.
Because your variable jsonResp contain string value not JSONObject so please first print and make sure is it string type value or not.
Hello I'm trying to use this endpoint www.reddit.com/reddits.json to show some list on android and I'm getting this error, below is my code.
I have this asynctask class on my main activity class:
private class AsyncListLoader extends AsyncTask<String, Integer, JSONObject>{
private JSONParser jsonParser = new JSONParser();
private static final String REDEEM_URL = "http://www.reddit.com/reddits.json";
private HashMap<String, String> param = new HashMap<>();
#Override
protected JSONObject doInBackground(String... params) {
JSONObject json = jsonParser.makeHttpRequest(REDEEM_URL, "GET", param);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
else {
Log.d("JSON result", "is null");
}
return null;
}
#Override
protected void onPostExecute(JSONObject s) {
try {
if(!s.has("kind")){
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
else {
JSONObject list = s.getJSONObject("data");
JSONArray childrens = list.getJSONArray("children");
for(int i = 0; i < childrens.length(); i++){
JSONObject o = childrens.getJSONObject(i).getJSONObject("data");
Feed f = new Feed(o.getString("icon_img"),o.getString("banner_img"),o.getString("display_name"));
MainActivity.this.adapter.add(f);
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
}
makehttpRequest when get:
if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
I tested out another json endpoints on the web and they are working. I dont have any idea why is this happening.
EDIT:
No param is being used so the url is fine.
The json is valid, I checked this in differents websites.
Everything seems to be fine except for the JSON exception error.
Here it is specifically: org.json.JSONException:
Value username of type `java.lang.String` cannot be converted to `JSONObject`.
There are a number of other flags that I can check in logcat and everything seems pretty good except that. I think the problem is that I need to convert the String encodedStr into a JSON object and return it to ASYNC TASK.
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Use HashMap, it works similar to NameValuePair
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", params[1]);
dataToSend.put("password", params[2]);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(serverUrl);
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString();//Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
**strong text**return encodedStr;**strong text**
**strong text**HERE IS THE PROBLEM I BELIEVE.
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if (result.equals("") || result == null) {
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
//************getEncodedData*****************//
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}`enter code here`
Hi I am new to android programming and I am working on a project that converts a list into json object and stores it in the server and retrieves it. I am able to send the json object to the server and store it but i am not able to retrieve it. What approach should i use to retrieve the json object stored on the server?
You can reffer bellow class ...... call getJSONfromURL(YOUR_JOSN_URL) and method will return you JSONObject.
I hope this will work
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
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, "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) {
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;
}
}
To retrieve JSON from server you have to establish a connection with server first by using DefaultHttpClient Hope you did that. If yes, post your code and if no then have look on
www.androidhive.info/2012/01/android-json-parsing-tutorial
Or google it you will lot of help to parse the JSON when you have URL with you.