基本的Gson帮助

时间:2011-03-08 06:43:20

标签: json gson

嗨我想要像dis数据一样的

  • buy_on_site
  • resource_uri
  • 资源
    • 出版商
      • 名称
      • resource_url
    • book_images
      • IMAGE_URL
      • FILE_TYPE
      • 名称
    • 作者
      • 名称
      • resource_uri

1 个答案:

答案 0 :(得分:1)

这是一个与问题中的结构相匹配的示例。

input.json内容:

{
    "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"
        }
    }
}

反序列化代码:

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);
  }
}