Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.gsontesting; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java_packages.Items; /** * * @author rory.crickmore */ public class ItemArrayDeserialiser implements JsonDeserializer<JsonItems> { /* Array deserialiser will put the items into an array and a seperate deserialiser will assign the correct fields. */ //Override needed since it's an abstract method. This will parse the Json data into Json objects to then be converted //into Java objects. @Override public JsonItems deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { //Create generic Json object. final JsonObject jsonObject = json.getAsJsonObject(); Items[] items = context.deserialize(jsonObject.get("Items"), Items[].class); final JsonItems arrObj = new JsonItems(); arrObj.setJsonItems(items); /* Example on how to get a Json field that isn't an array. final JsonElement jsonTitle = jsonObject.get("title"); final String title = jsonTitle.getAsString(); */ /*Example of getting an array at root level. final JsonArray jsonAuthorsArray = jsonObject.get("authors").getAsJsonArray(); final String[] authors = new String[jsonAuthorsArray.size()]; for (int i = 0; i < authors.length; i++) { final JsonElement jsonAuthor = jsonAuthorsArray.get(i); authors[i] = jsonAuthor.getAsString(); } */ return arrObj; } }