Here’s an example that matches the structure in the question.
input.json contents:
{
"next":"uri-to-next-page",
"previous":"uri-to-previous-page",
"total":12,
"buy_on_site":true,
"resource_uri":"uri-to-resource-1",
"resource":
{
"publisher":
{
"name":"publisher name 1",
"resource_uri":"uri-to-resource-2"
},
"book_images":
{
"image_url":"url-to-image",
"file_type":"PNG",
"name":"book-image-name"
},
"author":
{
"name":"author-name",
"resource_uri":"uri-to-resource-3"
}
}
}
The code to deserialize it:
import java.io.FileReader;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Foo
{
public static void main(String[] args) throws Exception
{
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
PublishedItem item = gson.fromJson(new FileReader("input.json"), PublishedItem.class);
System.out.println(item);
}
}
class PublishedItem
{
String next;
String previous;
int total;
boolean buyOnSite;
String resourceUri;
Resource resource;
@Override
public String toString()
{
return String.format(
"{PublishedItem: next=%s, previous=%s, total=%d, buyOnSite=%s, resourceUri=%s, resource=%s}",
next, previous, total, buyOnSite, resourceUri, resource);
}
}
class Resource
{
Publisher publisher;
Images bookImages;
Author author;
@Override
public String toString()
{
return String.format(
"{Resource: publisher=%s, bookImages=%s, author=%s}",
publisher, bookImages, author);
}
}
class Publisher
{
String name;
String resourceUri;
@Override
public String toString()
{
return String.format("{Publisher: name=%s, resourceUri=%s}", name, resourceUri);
}
}
class Images
{
String imageUrl;
FileType fileType;
String name;
@Override
public String toString()
{
return String.format("{Images: imageUrl=%s, fileType=%s, name=%s}", imageUrl, fileType, name);
}
}
enum FileType
{
PNG, JPEG, GIF
}
class Author
{
String name;
String resourceUri;
@Override
public String toString()
{
return String.format("{Author: name=%s, resourceUri=%s}", name, resourceUri);
}
}
solved Basic Gson Help [closed]