Exception on Converting string into json format - android

I am trying to convert this string
{result:
{data:
[
{id:6_99_First_99_Copy,name:First Copy},
{id:2_99_Third_99_View,name:Third View},
{id:9_99_test1,name:test1},
{id:3_99_Fourth_99_View,name:Fourth View},
{id:8_99_test,name:test}]
,status: success,message: Success.}}
to json format.
My code :
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is,
Charset.forName("utf-8")), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
//xmlString = sb.toString().replaceAll("\"", "\\\"");
xmlString = sb.toString().replaceAll("\"","\\\\\"");
newStr = xmlString.replaceAll("\\\\\\\\", "\\");
Log.w("Response Data: ", "" + newStr);
I have searched a lot but nothing is going to work , i tried to replace inverted commas as suggested in many post my output of above code is :
output :
{result: {data: [{\"id\":\"6_99_First_99_Copy\",\"name\":\"First Copy\"},{\"id\":\"2_99_Third_99_View\",\"name\":\"Third View\"},{\"id\":\"9_99_test1\",\"name\":\"test1\"},{\"id\":\"3_99_Fourth_99_View\",\"name\":\"Fourth View\"},{\"id\":\"4_99_Fifth_99_View\",\"name\":\"Fifth View\"},{\"id\":\"5_99_Sixth_99_View\",\"name\":\"Sixth View\"},{\"id\":\"7_99_First_99_View\",\"name\":\"First View\"},{\"id\":\"7_99_First_99_Copy\",\"name\":\"First Copy\"},{\"id\":\"1_99_Secon_99_View\",\"name\":\"Secon View\"},{\"id\":\"8_99_test\",\"name\":\"test\"}]
,status: success,message: Success.}}
I am getting this exception.
org.json.JSONException: Unterminated object at character 18 of {result: {data: [{id:6_99_First_99_Copy,name:First Copy},
Where I am doing wrong ?
Suggestion are greatly appreciated.

I would suggest, you better first validate your JSON string, Simply first log your converted string(JSON) and validate it, You may use this Json Validator
Once you are sure that your are resultant string in a correct JSON, then try the above.
Hope this helps

I think your returning JSON string is not a valid one. Use jsonlint for validating format. it will show the correct format and show errors if any.

Related

Parsing json object from google api returning null

I am making a simple application where i scan the barcode of a book and fetch its title and author from Google APIs,
Now, this is the url for json(for a particular book i am scanning)
https://www.googleapis.com/books/v1/volumes?q=isbn:9788120305960
using this code to get json in a string
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
response+=line;
}
bufferedReader.close();
inputStream.close();
urlConnection.disconnect();
Log.d("Info",response);
return response;
I store the result in a string and use this code to parse through
(json_response is a string)
JSONObject rootObject = new JSONObject(json_response);
JSONArray items = rootObject.getJSONArray("items");
JSONObject items_object = items.getJSONObject(0);
JSONObject volume_info = items_object.getJSONObject("volumeInfo");
book.setTitle(volume_info.getString("title"));
JSONArray authors = volume_info.getJSONArray("authors");
Log.d("Info","authors array length: "+authors.length());
String author="";
for (int i =0;i<authors.length();i++)
{
author+=authors.getString(i)+", ";
}
book.setAuthor(author);
The exception is:
Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
also I used logcat to see what is contained in json_response it looks something like this
null{ "kind": "books#volumes", "totalItems": 1, "items":...
The null here is probably causing the problem, so... any insights how to deal with this???
PS: I am a student , dealing first time with json and android, code is unprofessional, please pardon :)
Having
null{ "kind": "books#volumes", "totalItems": 1, "items":...
means that the response value has not been initialised.
You should therefore initialise it to empty string.

Error JSON com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle

I'm developing an application in Android where I can insert new comments (like in facebook or any other social network).
The function that does it is the following :
public static String putNewComment(String comment, int userId, int trackId) throws IOException,JSONException {
HttpPost post = new HttpPost(Globals.PUBLISH_NEW_COMMENT);
StringEntity input = new StringEntity("{\"comment\": \""+comment+"\",\"trackId\":"+trackId+",\"userId\":"+userId+"}");
input.setContentType("application/json;charset=UTF-8");
post.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
post.setHeader("Accept", "application/json");
post.setEntity(input);
HttpResponse response = client.execute(post,Globals.localContext);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String resultMy="";
String line;
while ((line = rd.readLine()) != null) {
resultMy+=line;
System.out.println("Server says: "+line);
}
return resultMy;
}
Every time I try to put a new comment that contains unicode characters like é,ò, and several others I get this error:
com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x22
Now, I am aware of the fact that the error is due to the fact that the content encoding is UTF-8 and I'm trying to insert an unicode character.
The problem is how to fix this? I tried by changing in this way :
input.setContentType("application/json;charset=UTF-16");
post.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-16"));
or
input.setContentType("application/json;charset=UTF-32");
post.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-32"));
But it doesn't work !
Please help me

how get return value from node js to android?

I create android apps as client and node as server, i got problem when i request value from android to node, i use this code in android to communicate with node js
String xResult = getRequestJSON("http://mydomain.com:8888");
public String getRequestJSON(String Url){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =requestJSON(response);
}catch(Exception ex){
}
return sret;
}
public static String requestJSON(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
and i got result like this in node.
[{"posid":"P0S6f50b314b2c279a2083cb0ef821ccb4d20140218120720","id_a":"ltv#ltv.com","gambar_a":"6f50b314b2c279a2083cb0ef821ccb4d.jpg","user":"lutfi soe","pwaktu":"2014-02-18T05:07:20.000Z","posnya":"test dr android","plat":-7.983757710988161,"plong":112.6549243927002,"pjenis":"I","vote":0}]
my question is,how i receive json like that in android ?and parse to string?
thanks
If you are receiving Json string in proper format then you can use JSON jar to parse this json.
You can get a tutorial for JSON parsing here
I think your question is more on how to parse and access the result in java[read Android].
Here is a solution that could help JavaScript type arrays in JAVA
JsonArray yourArray = new JsonParser()
.parse("[[\"2012-14-03\", 2]]")
.getAsJsonArray();
// Access your array like so - yourArray.get(0).getAsString();
// yourArray.get(0).getAsInt() etc
The above is using a library called Gson
P.S: I just plagiarized my own answer. Not sure what criteria to use to mark this question as a duplicate

Setting TextView's text as non-English text received from JSON response

I'm getting back names of (Foursquare) venues from a server call where the names of the venues returned can be in English or non-English.
Assume the venue name is in a JSON object as follows:
{...
"name":"venue name which can be in any language"
...}
I'm creating a JSONObject from this response and then pulling out the name of the venue as follows:
String name = jsonObject.getString("name");
Lastly, I'm setting the TextView's text to show the name of the venue as follows:
myTextView.setText(name);
I'm finding however for Arabic names that where the Arabic characters are joined in the original JSON object (as they should be), the characters that show in the app (i.e. in the TextView) are disjoint. (I'm not too familiar with other languages so can't really tell if they're showing incorrectly too.)
Is there something additional I should be doing to pull out non-English names correctly from the JSON object and setting it as the text of a TextView, or is it down to the phone to decide how the text will be displayed?
Edit: I've tried parsing the server response (as suggested by #bbedward) explicitly specifying the content encoding as UTF-8 as follows...
HttpEntity httpEntity = httpResponse.getEntity();
String responseMessage = EntityUtils.toString(myHttpEntity, "UTF-8");
JSONObject jsonObject = new JSONObject(responseMessage);
... but still no joy. (Arabic characters appear, as before, disjoint in words where they should be joint up.) Could it be a phone thing or is there something extra needing to be done myself to get the words/characters to show proper in non-English languages? Perhaps the server needs to explicitly specify a "Content-Type" header with value "UTF-8"?
I'm going to answer anyway, I'm guessing you aren't getting your json in UTF-8 as i had a similar problem, I believe json won't come any other way.
Complete Example
The only things to concern yourself with this is setting the encoding for the InputStreamReader and creating the JSONObject
private DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://myjsonurl.com/search?type=json");
// Depending on your web service
httppost.setHeader("Content-type", "application/json");
try
{
String result = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
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");
}
JSONObject myJObject = new JSONObject(sb.toString();
}
catch (Exception e)
{
}
finally
{
try{if(inputStream != null)inputStream.close();}catch(Exception none){}
}
add this line when you connect to mysql:
mysql_set_charset('utf8', $con);
ex:
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_set_charset('utf8', $con);
mysql_select_db(DB_DATABASE);

Using a buffer to convert http request responses to string in Android - Not getting entire response

I'm developing an app that posts to a site and I'm trying to store the entity response as a string. However, the string only seems to contain a small portion of the response, roughly 35 lines or so. I'm wondering if it has something to do with buffer overflow but really I am not sure. My code is below:
static String getResponseBody(HttpResponse response) throws IllegalStateException, IOException{
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null)
{
if(isBlankString(line) == false)
{
sb.append(line + "\n");
}
}
br.close();
content = sb.toString();
}
return content;
isBlankString just notes if a line doesn't contain any characters, as there's alot of blank lines in the response that were bugging me. I have the issue of not getting the whole response with or without this. Any body know what's going on or how to fix this?
Thanks
In my application I use just single line to get response string from entity:
final String responseText = EntityUtils.toString(response.getEntity());

Categories

Resources