2011-03-08 70 views
-6

您好我想收杆像DIS数据基本GSON帮助

  • 下一个
  • 以前
  • buy_on_site
  • resource_uri
  • 资源
    • 出版商
      • resource_url
    • book_images
      • IMAGE_URL
      • FILE_TYPE
    • 作者
      • resource_uri
+0

请注明您想回答的问题。 – 2011-03-08 23:37:00

回答

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