Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://my.server:8080/android/service.php");


List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "getjson"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

service.php generates a json string. How would i fetch it from my response? Btw; I've icluded the GSON library, can i make use of any methods in it perhaps?

Solutions similar to this one looks pretty ugly, imo: best way to handle json from httpresponse android

There much be better ways, right?

Any help is appreciated, thanks


Update:

String json = EntityUtils.toString(response.getEntity());

seems to do the trick. There is just one small issue: The string is wrapped with brackets []. Should i remove them manually? They are generated by php:s json_encode()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
300 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think the problem you are running into is one similar to my own I just ran into. If you run:

String json_string = EntityUtils.toString(response.getEntity());
JSONObject temp1 = new JSONObject(json_string);

The above code will throw an exception and it looks like the JSON array brackets are to blame. But it's fine to have a JSON array as the top level element! You just need to use JSONArray() instead of JSONObject:

String json_string = EntityUtils.toString(response.getEntity());
JSONArray temp1 = new JSONArray(json_string);

So you have to know if you are getting a JSONArray or a single dictionary that is a JSONObject in your JSON code.

If you are used to the iOS/Objective-C JSON parsing libraries they use the same top level element to deal with json dictionaries and json array's, so moving to the JAVA / Android world confused me about having two types for handling JSON depending on the top level returned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...