简体   繁体   中英

deserialize a json array using gson

I'm deserializing a json object like this:

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

As you can see, whenever there's a nested object I just refer to a class that has a toString() method for that particular nested json object. My question is: when the json object contains an array, which in my case just looks something like this:

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

...how do I use format.toString() to deserialize this array and then put it in my Offer toString() ?

Let's clarify the meaning of two terms.

  1. Serialize : To convert an object to a sequence of bytes.
  2. Deserialize : To parse (serialized data) so as to reconstruct the original object.

So @LuxuryMode, when you said "deserialize", did you mean "serialize"?

Assuming this is the case...

Note that your toString implementation does not currently properly generate a JSON object or array, or anything else that is valid JSON.

I recommend not using toString or any other hand-written implementation to serialize objects to JSON (or to XML or to bytes). If possible, use an API like Gson or Jackson (or XStream orthe Java Serialization API ).

The following example serializes a single Offer object.

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

This next example takes the JSON output from the previous example, and deserializes it back into a Java Offer object. You can add toString and/or equals implementations to verify that all of the attributes are populated as expected, but note that the toString method is not used by Gson during deserialization or serialization.

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

To serialize an array of Offer objects is similarly simple.

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

This final example takes the JSON array output from the previous example and deserializes it back into an array of Offer objects.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM