22 June 2015

Parsing JSON using gson

Annotations in java made our life easy for development!! In this post, I would explain how to parse JSON string from REST api using GSON, a google json parsing library. use user guide and refer this link to be familiar with more on gson(google json).

Assume, REST service will return following response

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{"Card": [
    {
        "CardNumber": "4544424719784129",
        "CardStatusID": "3",
        "ExpiryDate": "04/2017",
        "CardID": "1",
        "CardTypeID": "1",
        "AccountID": "1",
        "CardNotes": "",
        "GetCash": "1"
    },
    {
        "CardNumber": "4211472898719724",
        "CardStatusID": "3",
        "ExpiryDate": "05/2018",
        "CardID": "2",
        "CardTypeID": "2",
        "AccountID": "3",
        "CardNotes": "",
        "GetCash": "1"
    }]
}

Here, CardNumber, CardStatusID, ExpiryDate, CardID etc will be the primitive types and the block of content in "{}" will represent one object and pushed into java objects. The block "[]" represents an array of elements or start & end of array. The name "Card" is the key/name to the array. Again, curly braces around "Card" represent one object.

So, I have created 2 classes "Card.java" & "CardData.java". class "Card.java" will store all the primitives here and represent each block. "CardData.java" represent the entire block.

GSON can parse only primitive and user-defined types but not arrays etc.. For this to handle, we have to provide de-serializer helper class. A simple example that I have used here is as below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class CardListDeserializer implements JsonDeserializer<List<Card>> {
  public List<Card> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
      List<Card> list = new ArrayList<Card>();
      Gson gson = new Gson();
      list.addAll( Arrays.asList(gson.fromJson(json.getAsJsonArray(),Card[].class)) );
    
    return list;
  }
}

Below code snippet is for parsing the json response:

 1
 2
 3
 4
 5
 6
 7
 8
 9
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
class RESTClient {

    private static String LOST_CARDS_GET_URL = "http://server:port/services/json/showallcards";

    public static CardsData getLostCards(){
        CardsData cardsData = null;
        try {

            URL url = new URL(LOST_CARDS_GET_URL);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " +
                                           conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));;    

            
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(List.class, new CardListDeserializer());
            Gson gson = builder.create();
            cardsData  = gson.fromJson(br, CardsData.class);

            conn.disconnect();
            System.out.println(cardsData );
        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (Exception e) {

            e.printStackTrace();

        }

        return cardsData ;
    }

}

Below are the classes which have annotations to push respective primitives into variables.

 1
 2
 3
 4
 5
 6
 7
 8
 9
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
import com.google.gson.annotations.SerializedName;

public class Card {

    @SerializedName("CardNumber")
    private String cardNumber;
    @SerializedName("CardStatusID")
    private String cardStatusID;
    @SerializedName("ExpiryDate")
    private String expiryDate;
    @SerializedName("CardID")
    private String cardID;
    @SerializedName("CardTypeID")
    private String cardTypeID;
    @SerializedName("AccountID")
    private String accountID;
    @SerializedName("CardNotes")
    private String cardNotes;
    @SerializedName("GetCash")
    private String getCashFlag;
    
    public Card() {
        super();
    }


    public void setCardID(String cardID) {
        this.cardID = cardID;
    }

    public String getCardID() {
        return cardID;
    }

    public void setAccountID(String accountID) {
        this.accountID = accountID;
    }

    public String getAccountID() {
        return accountID;
    }

    public void setCardNotes(String cardNotes) {
        this.cardNotes = cardNotes;
    }

    public String getCardNotes() {
        return cardNotes;
    }

    public void setCardNumber(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    public String getCardNumber() {
        return cardNumber;
    }

    public void setExpiryDate(String expiryDate) {
        this.expiryDate = expiryDate;
    }

    public String getExpiryDate() {
        return expiryDate;
    }

    public void setCardStatusID(String cardStatusID) {
        this.cardStatusID = cardStatusID;
    }

    public String getCardStatusID() {
        return cardStatusID;
    }

    public void setCardTypeID(String cardTypeID) {
        this.cardTypeID = cardTypeID;
    }

    public String getCardTypeID() {
        return cardTypeID;
    }

    public void setGetCashFlag(String getCashFlag) {
        this.getCashFlag = getCashFlag;
    }

    public String getGetCashFlag() {
        return getCashFlag;
    }
}

Here is the wrapper class which holds the list of "Card" objects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class CardData {
    
    @SerializedName("Card")
    private List<Card> cardsList;
    public CardList() {
        super();
    }


    public void setCardsList(List<Card> cardsList) {
        this.cardsList = cardsList;
    }

    public List<Card> getCardsList() {
        return cardsList;
    }
}

No comments :

Post a Comment