I got a valid Json string(at least every onlinevalidator I tried says so) which contains some chinese characters.
The json string is the following:
{"title":"\u8981\u805e--\u83ef\u723e\u8857\u65e5\u5831","url":"http://cn.wsj.com","desc":"\u300a\u83ef\u723e\u8857\u65e5\u5831\u300b\u4e2d\u6587\u7db2\u7d61\u7248\u6700\u65b0\u8ca1\u7d93\u8981\u805e","imageUrl":null,"lastUpdate":"1327588937","items":[{"title":"\u4e16\u8cbf\u7d44\u7e54\u7e3d\u5e79\u4e8b\ufe55\u4eba\u6c11\u5e63\u5e63\u503c\u88ab\u4f4e\u4f30\ufe50\u4f46\u4f4e\u4f30\u7a0b\u5ea6\u4e0d\u660e","desc":"\u4e16\u754c\u8cbf\u6613\u7d44\u7e54\u7e3d\u5e79\u4e8b\u5e15\u65af\u5361\u723e\uff0e\u62c9\u7c73\u9031\u56db\u8868\u793a\ufe50\u4eba\u6c11\u5e63\u532f\u7387\u88ab\u660e\u986f\u4f4e\u4f30\ufe50\u4f46\u4f4e\u4f30\u7a0b\u5ea6\u9084\u4e0d\u6e05\u695a\u3002","url":"http://cn.wsj.com/big5/20120126/BCHc-20120126WR182711424.asp?source=rss","pubdate":null}]}
Now when i Parse the JsonString in Android via new JsonObject(jsonString) I only got some squares instead of characters.
Why cant android handle this json string?
Any help would be apreciated.
If anyone would like to have the server Ressource, it can be found under:
// edit
url removed
public static String test(){
String testResult= "";
try {
HttpGet get = new HttpGet("http://xxxxx");//edit url removed.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(get);
String result = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(result);
if(!obj.isNull("title")){
testResult= obj.getString("title");
Log.d("Test","Test1:"+ testResult);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return testResult;//
}
and Then TextView.setText(testResult);
It works for me.
it's Traditional Chinese String:"要聞--華爾街日報"
May be your ROM has no Traditional Chinese font????
When you receive your JSON, you may have to decode the UTF-8 result when you're building your result. Have a look at utf8 decoding. Something similar to this, but with JSON
Related
Am I missing something, I am trying to create a loginActivity and I created this code, and I have a log that logs the answer to the volley I created...But The if statement is not getting entered...Can someone see something I'm doing wrong? Sorry if its really dump( and yes I tried to change the response.equals check to be response.equals(" Password Accepted!");, this did not work either)
Another thing to note, yes I know my search in the log is different then the tag, it doesnt login, (which is what i want it to do)
Toast.makeText(getApplication(), response, Toast.LENGTH_LONG).show();
Log.e("Before Conversion",response);
String convertedResponse = null;
try {
convertedResponse = new String(response.getBytes("ISO-8859-1"), "UTF-8");
L.e("After Conversion",convertedResponse);
if (convertedResponse.equals("Password Accepted!")) {
showProgress(false);
Message msg = new Message();
msg.what = 1;
msg.obj = succcess ? 1 : 0;
handler.sendMessage(msg);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
06-29 15:24:04.990 16707-16707/E/Before Conversion: Password Accepted!
06-29 15:24:04.990 16707-16707/E/After Conversion: Password Accepted!
After suggestion to change logging...
06-29 15:34:32.339 16707-16707/ E/Got a response:: Password Accepted!
UPDATE
After creating a JSON array of length 1 with just the response string and a key for it, and passing it to my android studio code, the json array wont parse through the functions used to parse it (JSON Object, JSON Array), but manually parsing the response string works..... Less graceful then I would like it but i guess it works....
This can happen when encoding of response is not UTF-8. Try converting response like this:
String convertedResponse = null;
try {
convertedResponse = new String(response.getBytes("ISO-8859-1"), "UTF-8");
// do your things ...
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
your response is in JSONObject not JSONArray, so on Response Listnere use:
if(response.getString("response").equals("PASSWORD ACCEPTED!"){
//do what you want to do
}
I'm currently sending an image to my server by encoding it into a base64 string like this: https://gist.github.com/fabdarice/a4006a97171cc415892e
However, when I'm looking at the HTTP POST request, I'm seeing something like this :
{"login"=>"Jerem", "mobile_upload_file"=>"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAQ4BDgDASIA\nAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA\nAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3\nODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm\np6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA\nAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3....................................}
This goes on for a while, (around 1 millions characters) and it seems to make my server laggy.
I was wondering if this is a normal behavior to see that amount of characters sent? If not, how am I supposed to implement the process of sending an image to a server?
Thanks for your help
You can send image in FileBody by Multipart entity like this...
public String sendMultipartRequestToServer(BusinessDataObject dataObject,String url) {
String responseString=null;
HttpResponse response;
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
HttpConnectionParams.setConnectionTimeout(client.getParams(),50000);
MultipartEntity multipartEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
multipartEntity.addPart(KEY_EMAIL,new StringBody(dataObject.getEmail()));
multipartEntity.addPart(KEY_PASSWORD, new StringBody(dataObject.getPassword()));
multipartEntity.addPart(KEY_IMAGE,new FileBody(new File(Here your image path on your memory)));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Setting parameter to post method
post.setEntity(multipartEntity);
try {
response=client.execute(post);
InputStream inputStream=response.getEntity().getContent();
responseString=convertStreamToString(inputStream);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
If you will not find the class MultipartEntity .Then you have to add HttpMime.jar in your project .It is the best way to send images so far i know here no need to convert image in Base64.You can just pass the url of selected image to FileBody.
I'm trying to download a JSON file in this format
[
{
"CRN":"10001",
"Course":"REG1"
},
{
"CRN":"10002",
"Course":"REG2"
}
]
I understand how to use a JSONArray class once it is created but I don't know how to create the JSONArray object from the file. If the URL location of the file were to be "www.test.com" how would I go about downloading it in background upon the launch of my application so as to not interfere with the launching of the app but not require the user to manually download it themselves.
You might want to check out this helpful library: Retrofit
It makes grabbing and parsing JSON data easy!
I think you should look for Android Web Service example. Where you can find info about
1.How to make a HTTP request to server (using URL eg. www.google.com)
2. How to handle Response from Server
3. How to parse JSON/XML response from Server etc.
Here is the Simple Tutorial I Found for you.
Android Web service for Log-in and Registration
Just go through step by step.
In the example we are making request to server for login and getting response then going ahead in app.
Here is the code snipp.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
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, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} 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;
}
}
A good way to download the JSON file automatically, would be to launch an AsyncTask during your onCreate method of the home activity.
JSON files are nothing more than text files in a special format, so the could be easily downloaded as a response from a HttpURLConnection, and then be treated as a String.
A suggestion for parsing the JSON objets into Java objects would be the Jackson JSON Processor. You could use the class ObjectMapper of this library to automatically create the objects.
If you are planing to implement the server side by yourself, and you also need a library to send JSON objects, you could use Jersey on both server and client.
Im doing a simple http get,
I see on my result an incomplete response,
what Im doing wrong?
here the code:
class GetDocuments extends AsyncTask<URL, Void, Void> {
#Override
protected Void doInBackground(URL... urls) {
Log.d("mensa", "bajando");
//place proper url
connect(urls);
return null;
}
public static void connect(URL[] urls)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet("http://tiks.document.dev.chocolatecoded.com.au/documents/api/get?type=tree");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.d("mensa",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
Log.d("mensa", "estratagema :: "+result);
JSONObject jObject = new JSONObject(result);
Log.d("mensa", "resposta jObject::"+jObject);
Log.d("mensa", "alive 1");
JSONArray contacts = null;
contacts = jObject.getJSONArray("success");
Log.d("mensa", "resposta jObject::"+contacts);
Log.d("mensa", "alive");
//instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.d("mensa", "linea ::"+line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
i call it with:
GetDocuments get = new GetDocuments();
URL url = null;
try {
url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//URL url = new URL("http://www.google.es");
get.execute(url);
edit 1
I refer to incomplete as the response that gets truncated?
please notice in below image of response how string gets truncated,
is this because of the log size?,
but the other problem is that it doesn't parse?
thanks!
I don't know if this is going to resolve your problem but you can get rid of your method and use simply:
String responseString = EntityUtils.toString(response.getEntity());
I've had exactly the same issue for the last couple of days. I found that my code worked over WiFi but not 3G. In other words I eliminated all the usual threading candidates. I also found that when I ran the code in the debugger and just waited for (say) 10 seconds after client.execute(...) it worked.
My guess is that
response = httpclient.execute(httpget);
is an asynchronous call in itself and when it's slow returns a partial result... hence JSON deserialization goes wrong.
Instead I tried this version of execute with a callback...
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String json = httpclient.execute(httpget, responseHandler);
} finally {
httpclient.close();
}
And suddenly it all works. If you don't want a string, or want your own code then have a look at the ResponseHandler interface. Hope that helps.
I have confirmed that this is because size limit of java string. I have checked this by adding the string "abcd" with the ressponse and printed the response string in logcat. But the result is the truncated respose without added string "abcd".
That is
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String json = httpclient.execute(httpget, responseHandler);
json= json+"abcd";
Log.d("Json ResponseString", json);
} finally {
httpclient.close();
}
So I put an arrayString to collect the response. To make array, I splitted My json format response by using "}"
The code is given below(This is a work around only)
BasicResponseHandler responseHandler = new BasicResponseHandler();
String[] array=client.execute(request, responseHandler).split("}");
Then you can parse each objects in to a json object and json array with your custom classes.
If you get any other good method to store response, pls share because i am creating custom method for every different json responses );.
Thank you
Arshad
Hi Now I am using Gson library to handle the responses.
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Thanks
Arshad
I cant' comment directly due to reputation, but in response to https://stackoverflow.com/a/23247290/4830567 I felt I should point out that the size limit of a Java String is about 2GB (Integer.MAX_VALUE) so this wasn't the cause of the truncation here.
According to https://groups.google.com/d/msg/android-developers/g4YkmrFST6A/z8K3vSdgwEkJ it is logcat that has a size limit, which is why appending "abcd" and printing in logcat didn't work. The String itself would have had the appended characters. The previously linked discussion also mentioned that size limits with the HTTP protocol itself can occasionally be a factor, but that most servers and clients handle this constraint internally so as to not expose it to the user.
I have written a web application to run on Google AppEngine using the Restlet framework, communicating using json with web clients. Those work as expected. However, one specific resource written to provide response to an Android client doesn't work when accessed through Android. However, it does work when accessed through a web browser (I do not send the request parameters from the browser and thus get a 400 which is ok in this case).
This code works when running on the DevAppServer:
public class PlayResource extends ServerResource {
private final float SCOREBASE = 1000.0F;
#Get
#Post
public JsonRepresentation play() {
try {
JsonRepresentation rep = new JsonRepresentation(getRequestEntity());
JSONObject inputJson = rep.getJsonObject();
JSONObject outputJson = new JSONObject();
String country = inputJson.optString("country");
outputJson.put("country", doSomething("country",country));
......
......
return new JsonRepresentation(outputJson);
} catch (IOException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_REQUEST));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
} catch (JSONException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_FORMAT));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
}
}
and the client Android device is running this code:
Client client = new Client(Protocol.HTTP);
try {
JsonRepresentation requestJSON = new JsonRepresentation(new JSONObject()
.put("country", country.trim())
);
Request req = new Request(Method.GET,"http://****.appspot.com/resource/play",requestJSON);
Response resp = client.handle(req);
String res = resp.getEntity().getText();
JSONObject resultJSON = new JSONObject(res);
Running this request just hangs the Android client, the server doesn't write any log messages whatsoever suggesting the request doesn't arrive there.
It seems that it's more a Appengine/Java issue than an android issue, but...let's try something else:
instead of using Client and the stuff u are using, first just try to see what the server responds to the simplest connection (as you do in a web browser):
URL url;
try {
url = new URL("http://yourappid.appspot.com/resource/play");
String content = (String) url.getContent();
System.out.println(content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If it works and you get your expeted 400, if so...try to send an httppostrequest with the data...like this:
HttpClient client = new DefaultHttpClient();
HttpUriRequest httpRequest = new HttpPost("http://yourappid.appspot.com/resource/play");
//set the content type to json
httpRequest.setHeader("Content-Type", "application/json");
//get and work with the response
HttpResponse httpResponse = client.execute(httpRequest);
Let me know if the answer was useful