使用gson反序列化json数组

时间:2011-06-05 14:41:38

标签: java json gson

我正在反序列化这样的json对象:

class Offer
{
    private Category category;
    private String description;
    private String discount;
    private Date expiration;
    private Date published;
    private String rescinded_at;
    private String title;
    private Date valid_from;
    private Date valid_to;
    private String id;
    private Business business;
    private Location location;
    private Long distance;


    public String getDescription() {
        return String.format("[Offer: description=%2$s]", description);

    }

    @Override
    public String toString()
    {
        return String.format(
                "[Offer: category=%1$s, description=%2$s, discount=%3$s, expiration=%4$s, published=%5$s, rescinded_at=%6$s, title=%7$s, valid_from=%8$s, valid_to=%9$s, id=%10$s, business=%11$s, location=%12$s, distance=%13$s]",
                category, description, discount, expiration, published, rescinded_at, title, valid_from, valid_to, id,
                business, location, distance);
    }
}

正如您所看到的,只要有嵌套对象,我就会引用一个对该特定嵌套json对象具有toString()方法的类。我的问题是:当json对象包含一个数组时,在我的例子中看起来像这样:

"draws":[ "Hair Cut", "Blow Dry", "Blow Dry Treatment" ]

...如何使用format.toString()反序列化此数组,然后将其放入我的Offer toString()

1 个答案:

答案 0 :(得分:0)

让我们澄清两个术语的含义。

  1. Serialize:将对象转换为字节序列。
  2. Deserialize:解析(序列化数据)以重建原始对象。
  3. 所以@LuxuryMode,当你说"反序列化"时,你的意思是"序列化"?

    假设情况属实......

    请注意,您的toString实现目前无法正确生成JSON对象或数组,或其他任何有效的JSON。

    我建议不要使用toString或任何其他手写实现来将对象序列化为JSON(或XML或字节)。如果可能,请使用GsonJackson(或XStreamthe Java Serialization API)等API。

    以下示例序列化单个Offer对象。

    // output:
    // {
    //  "category":
    //  {
    //      "name":"category_1",
    //      "type":1
    //  },
    //  "description":"description_1",
    //  "discount":"discount_1",
    //  "expiration":
    //  {
    //      "value":123
    //  },
    //  "published":
    //  {
    //      "value":456
    //  },
    //  "rescinded_at":"rescinded_at_1",
    //  "title":"title_1",
    //  "valid_from":
    //  {
    //      "value":789
    //  },
    //  "valid_to":
    //  {
    //      "value":987
    //  },
    //  "id":"id_1",
    //  "business":
    //  {
    //      "name":"business_name_1",
    //      "opening_date":
    //      {
    //          "value":654
    //      }
    //  },
    //  "location":
    //  {
    //      "latitude":111,
    //      "longitude":222
    //  },
    //  "distance":333
    //}
    
    import com.google.gson.FieldNamingPolicy;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class Foo
    {
      public static void main(String[] args)
      {
        Offer offer = new Offer(
            new Category("category_1", 1), 
            "description_1", 
            "discount_1", 
            new Date(123), 
            new Date(456), 
            "rescinded_at_1", 
            "title_1", 
            new Date(789), 
            new Date(987), 
            "id_1", 
            new Business("business_name_1", new Date(654)), 
            new Location(111, 222), 
            new Long(333));
    
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        Gson gson = gsonBuilder.create();
        String offerJson = gson.toJson(offer);
        System.out.println(offerJson);
      }
    }
    
    class Offer
    {
      private Category category;
      private String description;
      private String discount;
      private Date expiration;
      private Date published;
      private String rescindedAt;
      private String title;
      private Date validFrom;
      private Date validTo;
      private String id;
      private Business business;
      private Location location;
      private Long distance;
    
      Offer(Category category, 
          String description, 
          String discount, 
          Date expiration, 
          Date published, 
          String rescindedAt, 
          String title, 
          Date validFrom, 
          Date validTo, 
          String id, 
          Business business, 
          Location location, 
          Long distance)
      {
        this.category = category;
        this.description = description;
        this.discount = discount;
        this.expiration = expiration;
        this.published = published;
        this.rescindedAt = rescindedAt;
        this.title = title;
        this.validFrom = validFrom;
        this.validTo = validTo;
        this.id = id;
        this.business = business;
        this.location = location;
        this.distance = distance;
      }
    }
    
    class Category
    {
      private String name;
      private int type;
    
      Category(String name, int type)
      {
        this.name = name;
        this.type = type;
      }
    }
    
    class Date
    {
      private long value;
    
      Date(long value)
      {
        this.value = value;
      }
    }
    
    class Business
    {
      private String name;
      private Date openingDate;
    
      Business(String name, Date openingDate)
      {
        this.name = name;
        this.openingDate = openingDate;
      }
    }
    
    class Location
    {
      private int latitude;
      private int longitude;
    
      Location(int latitude, int longitude)
      {
        this.latitude = latitude;
        this.longitude = longitude;
      }
    }
    

    下一个示例接受上一个示例中的JSON输出,并将其反序列化为Java Offer对象。您可以添加toString和/或equals实现来验证是否按预期填充了所有属性,但请注意,在反序列化或序列化期间Gson不使用toString方法。 / p>

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    Gson gson = gsonBuilder.create();
    String offerJson = gson.toJson(offer);
    
    Offer offerDeserialized = gson.fromJson(offerJson, Offer.class);
    

    序列化Offer个对象的数组同样简单。

    Offer offer1 = new Offer(
        new Category("category_1", 1), 
        "description_1", 
        "discount_1", 
        new Date(123), 
        new Date(456), 
        "rescinded_at_1", 
        "title_1", 
        new Date(789), 
        new Date(987), 
        "id_1", 
        new Business("business_name_1", new Date(654)), 
        new Location(111, 222), 
        new Long(333));
    
    Offer offer2 = new Offer(
        new Category("category_2", 2), 
        "description_2", 
        "discount_2", 
        new Date(234), 
        new Date(567), 
        "rescinded_at_2", 
        "title_2", 
        new Date(890), 
        new Date(876), 
        "id_2", 
        new Business("business_name_2", new Date(543)), 
        new Location(444, 555), 
        new Long(666));
    
    Offer[] offers = new Offer[] {offer1, offer2};
    
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    Gson gson = gsonBuilder.create();
    String offersJson = gson.toJson(offers);
    System.out.println(offersJson);
    

    这个最后一个示例获取前一个示例中的JSON数组输出,并将其反序列化为一个Offer个对象数组。

    Offer[] offersDeserialized = gson.fromJson(offersJson, Offer[].class);