I am having some issues while parsing JSON response in Android. The response I get is:
{
"response": "{\"session_token\":\"48500d8e42acc09aa45cb8f3a7ba2b30\",\"user_login\":\"newoff2\",\"user_id\":\"62\",\"user_profile_img\":\"http://onepgr.com/system/photos/62/medium/userfile054c35e29.png?1422089771\",\"success\":\"0\",\"user_email\":\"newoff2#pdmoffice.com\"}"
}
I need the values for user_login, success, user_profile_img, user_email. Here is what I tried so far, but it won't do what I need:
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
Log.d("Final Response",json);
jsonObject = new JSONObject(json);
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
Log.e("Parsed data is",str);
use this
json=json.replace("\\\"", "\"");
Log.e("resule",json);
try {
JSONObject jsonObject = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use regex to make your string JSON parsable
var res = data.replace(/\\"/g, '').replace(/\"{/g, '{').replace(/\}"/g, '}');
var jsonData = JSON.parse(res);
alert(jsonData.response.user_login);
Here is FIDDLE
Note: in fiddle I have declared your JSON with a ' ' to make it complete string
Use Scanner to remove \:
String resultStr = new Scanner(json).useDelimiter("\\A").next();
jsonObject = new JSONObject(resultStr);
Above is used for BufferedInputStream to get JSON string.
[UPDATE:]
For BufferReader, need to use StringBuilder to get JSON string:
StringBuilder strBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
//for your JSON string, should use 'JSONTokener' to parse
jsonObject = (JSONObject) new JSONTokener(strBuilder.toString()).nextValue();
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
This should work for your case!
Try this....
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();
Log.d("Result",result);
JSONObject jsonObject = new JSONObject(result);
String resJson=jsonObject.getString("response");
Log.d("Result",resJson);
JSONObject jsparam=new JSONObject(resJson);
String success=jsparam.getString("success");
Log.d("Value for success",success);
// JSONObject json1=jsonObject.getJSONObject("response");
//String objResponse = json1.getString("success");
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
Related
I have a problem with Java when I try to display all of content from cmd's elements. So here is my code:
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonElement data = jsonObject.get("data");
System.out.println(data);
// Close connection
in.close();
}
Output:
[{"cmd":"cmd-1"},{"cmd":"cmd-2"},{"cmd":"cmd-3"}]
I want to use foreach of cmd to display the following:
cmd-1
cmd-2
cmd-3
Try this code. I hope it helps.
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonArray data = jsonObject.getAsJsonArray("data");
//here data is JsonArray and it contains everithing: [{"cmd":"cmd-1"},{"cmd":"cmd-1"},{"cmd":"cmd-1"}]
data.forEach(el -> {
//Get Json object which has key and value -> {"cmd":"cmd-1"}
JsonObject jo = el.getAsJsonObject();
//get the value as Json element -> "cmd-1"
JsonElement je = jo.get("cmd");
//Then make the json element string
String value = je.getAsString();
System.out.println(value);
});
//System.out.println(data);
// Close connection
in.close();
}
i am trying to get the data from database through a php file and then i want to use that data in android.i have tried a lot but it show me this error:type org.json.JSONObject cannot be converted to JSONArray.
followin is my php file and android code.also json array which was return is valid.
<?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'";
$res = mysqli_query($con,$sql) or die('i cant');
//$result = array();
$abc="";
while($row = mysqli_fetch_assoc($res)){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
$final = array("result"=>$abc);
//echo json_encode(array("result"=>$result));
echo json_encode($final);
mysqli_close($con);
?>
andoid code
public void searchProfession() {
//testin work
String[] stringArray = new String[5];
//
try {
HttpParams httpParams = new BasicHttpParams();
HttpParams p = new BasicHttpParams();
p.setParameter("profession", SearchProfession);
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://abh.netai.net/abhfiles/searchProfession.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//fffffffffffffffffffffffffff
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
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);
// 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");
}
result = sb.toString();
// return JSON String
if (inputStream != null) inputStream.close();
//ffffffffffffffffffffffffffff
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("result");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//testin work
String[] myarray;
//till here
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString(i);
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0], Toast.LENGTH_SHORT).show();
mylist.add(map);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
My Json : [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769642","crtloc_lng":"72.361160"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]
now i want to get the data in result array and show that data in android.for example i want to use all the(user_id) from that array
I think you got this error because jArray.getJSONObject(0); when i = 0 it's an array not an Object
your Json [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},...]
So jArray.getJSONObject(0); is [] not an object {"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"}
You can check out this post on how to execute GET/POST/MULTIPART POST requests in android and then use that post to see how to parse your JSON data into pojo(s).
Hope that helps.
The error:type org.json.JSONObject cannot be converted to JSONArray is thrown when you try to fetch a JSONObject in the place of an array. An exception will also be thrown if you try to fetch empty objects so please check your code for empties.
start by
$abc="";
while($row = mysqli_fetch_assoc($res)){
if(!empty($row['user_id'])&&!empty($row['crtloc_lat'])&&!empty($row['crtloc_lng'])){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
}
Then
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString("crtloc_lat");//Use a key here
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0],Toast.LENGTH_SHORT).show();
mylist.add(map);
}
I have am trying to convert my response from a POST to JSON. And here is what I am doing:
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line).append("\r");
}
rd.close();
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response.toString());
But then I get error java.lang.String cannot be converted to JSONObject
But if I make a string, String string; and then I paste the what I logged and set it equal to string, and then try
JSONObject jsonObject = new JSONObject(string);
It works, so why is it working when I paste the logged response, but not when I just use response.toString();?
In the logcat it looks like this {"url": "www.google.com"}. And then when I paste it into string = "{\"url\": \"www.google.com\"}";
Thanks for the help
I met this problem before, try this:
new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
or
if (response != null && response.startsWith("\ufeff")) {
in = in.substring(1);
}
the response from server contains a BOM header
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string.
source - A string beginning with { (left brace) and ending with } (right brace).
So while doing response.toString() if the string do not start with { and close with } then it will throw Exception.
Here's the twitch.tv api request to get channel summary: http://api.justin.tv/api/streams/summary.json?channel=mychannel. If I post it via browser, I get correct results. But programmatically I receive an exception during result parsing.
I use apache HttpClient to send requests and receive responses. And JSON-Simple to parse JSON content.
This is how I try to get JSON from response according to api:
HttpClient httpClient = HttpClients.createDefault();
HttpGet getRequest = new HttpGet(new URL("http://api.justin.tv/api/streams/summary.json?channel=mychannel").toURI());
getRequest.addHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String output;
StringBuilder builder = new StringBuilder();
while((output = br.readLine()) != null) {
builder.append(output);
}
br.close();
JSONParser parser = new JSONParser();
Object obj = parser.parse(builder.toString()); //Exception occurs here
Expected result: {"average_bitrate":0,"viewers_count":"0","streams_count":0}, but execution of example above leads to: Unexpected character (<) at position 0.
How to get JSON body from response? Browser displays the result correct.
Try this:
URL url = new URL("http://api.justin.tv/api/stream/summary.json?channel=mychannel");
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
request1.setRequestMethod("GET");
request1.connect();
InputStream is = request1.getInputStream();
BufferedReader bf_reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = bf_reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
String responseBody = sb.toString();
JSONParser parser = new JSONParser();
Object obj = parser.parse(responseBody);
System.out.println(obj);
When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
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());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
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());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.