Json parse from webserver in android or android studio

First you have to aware about this, reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

Now , How to parse json getting from webserver.

DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.1.100/response.php");
httppost.setHeader("Content-type", "application/json");

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();
} catch (Exception e) { 
    e.printStack();
}
finally {
    try{
if(inputStream != null)
inputStream.close();
}catch(Exception e){
e.printStack();
}
}

Now you have to create JsonObject


Create a JSONObject like this:

JSONObject jObject = new JSONObject(result);

and parse your requirement.


Happy Coding !!!

Json parse from webserver in android or android studio Json parse from webserver in android or android studio Reviewed by D Kshetri on 9:10 PM Rating: 5

No comments:

Powered by Blogger.