The Ajax (Asynchronous JavaScript and XML).
You either want to integrate with a web service that only supports JSON, or you want to take advantage of JSON’s benefits such as being able to efficiently create and manage
textual representations of data structures in memory.
how this book could be modeled in JSON:
{ "title": "Android in Practice", "price": 49.99, "authors": [ { "name": "C. Collins" }, { "name": "M. Galpin" }, { "name": "M. Kaeppler" } ] }
JSON response format of TMDb’s Movie.imdbLookup method:
[ { "popularity":3, "translated":true, "adult":false, "language":"en", "original_name":"Inception", "name":"Inception", "alternative_name":"Eredet", "movie_type":"movie", "id":27205, "imdb_id":"tt1375666", "url":"http://www.themoviedb.org/movie/27205", "votes":52, "rating":9.0, "certification":"PG-13", "overview":"Dom Cobb (Leonardo DiCaprio) is a skilled thief, the best in the dangerous art of extraction: stealing valuable secrets from deep within the subconscious during the dream state when the mind is at its most vulnerable. ...", "released":"2010-07-16", "runtime":148, "version":226, "last_modified_at":"2010-08-19 16:04:03", ... } ]
JsonMovieParser parses a TMDb movie document using JSON
public class JsonMovieParser { public static Movie parseMovie(InputStream json)throws Exception{ BufferedReader reader=new BufferedReader(new InputStreamReader(json)); StringBuilder sb=new StringBuilder();//holds server response as string try{ String line=reader.readLine(); while(line!=null){ sb.append(line); line=reader.readLine(); } }catch(IOException e){ throw e; }finally{ reader.close(); } //turn string into a JSONObject JSONArray jsonReply=new JSONArray(sb.toString()); Movie movie=new Movie(); //get Movie JSONObject JSONObject jsonMovie=jsonReply.getJSONObject(0); movie.setTitle(jsonMovie.getString("name")); movie.setRating(jsonMovie.getString("rating")); return movie; } }
The JSON parser relies on the data being in memory entirely, so we have to read the response string into a buffer first B. We can then use this string to instantiate a JSON
object (a JSONArray in this case, because the root element is an array), which effectively parses the JSON string into an internal key-value map C. We’re interested in the
first and only element of the array, so we get the JSONObject at position 0, which is the movie we’re after.
One implication of this is that the json.org parser may not be optimal if you need to access a small amount of data from a large document. You probably don’t want to
parse several megabytes of text into a JSON object because it’ll be in memory all at once.
If you can’t live with that, then XmlPull is probably your best bet.
which return null if the field you’re trying to access doesn’t exist.
use optString instead of getString for accessing an optional string field.