json
JSON parsing with Gson
This is an example of JSON parsing on Android with Gson. Google Gson is a Java library that can be used to convert Java Objects into their JSON representation.
In order to parse JSON with Gson, follow these steps:
- Create a class that extends Activity (here called JsonParsingActivity)
- Create an instance of the
Gson
class - Use the DefaultHttpClient to retrieve the data if this is a web resource
- Create a class that will represent the model of the input (here called SearchResponse)
- Use the
fromJson
method in order to parse the JSON input and return the model object
These are demonstrated in the code snippet(s) below:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | package com.javacodegeeks.android.json; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.gson.Gson; import com.javacodegeeks.android.json.model.Result; import com.javacodegeeks.android.json.model.SearchResponse; public class JsonParsingActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); InputStream source = retrieveStream(url); Gson gson = new Gson(); Reader reader = new InputStreamReader(source); SearchResponse response = gson.fromJson(reader, SearchResponse. class ); Toast.makeText( this , response.query, Toast.LENGTH_SHORT).show(); List<Result> results = response.results; for (Result result : results) { Toast.makeText( this , result.fromUser, Toast.LENGTH_SHORT).show(); } } private InputStream retrieveStream(String url) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null ; } HttpEntity getResponseEntity = getResponse.getEntity(); return getResponseEntity.getContent(); } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null ; } } |
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | package com.javacodegeeks.android.json.model; import java.util.List; import com.google.gson.annotations.SerializedName; public class SearchResponse { public List results; @SerializedName ( "max_id" ) public long maxId; @SerializedName ( "since_id" ) public int sinceId; @SerializedName ( "refresh_url" ) public String refreshUrl; @SerializedName ( "next_page" ) public String nextPage; @SerializedName ( "results_per_page" ) public int resultsPerPage; public int page; @SerializedName ( "completed_in" ) public double completedIn; @SerializedName ( "since_id_str" ) public String sinceIdStr; @SerializedName ( "max_id_str" ) public String maxIdStr; public String query; } |
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | package com.javacodegeeks.android.json.model; import com.google.gson.annotations.SerializedName; public class Result { @SerializedName ( "from_user_id_str" ) public String fromUserIdStr; @SerializedName ( "profile_image_url" ) public String profileImageUrl; @SerializedName ( "created_at" ) public String createdAt; @SerializedName ( "from_user" ) public String fromUser; @SerializedName ( "id_str" ) public String idStr; public Metadata metadata; @SerializedName ( "to_user_id" ) public String toUserId; public String text; public long id; @SerializedName ( "from_user_id" ) public String from_user_id; @SerializedName ( "iso_language_code" ) public String isoLanguageCode; @SerializedName ( "to_user_id_str" ) public String toUserIdStr; public String source; } |
01 02 03 04 05 06 07 08 09 10 | package com.javacodegeeks.android.json.model; import com.google.gson.annotations.SerializedName; public class Metadata { @SerializedName ( "result_type" ) public String resultType; } |
This was an example of how to parse JSON with Gson on Android.
Related Article: