简体   繁体   中英

JSON inner field parsing with GSON

I am new to JSON and I love how incredibly potent and straight-forward GSON Api can be, compared to any other parsing methods I've researched.
I want to parse a rather complex JSON(using GSON) that resembles the following one in terms of structure:

[
  {  
  "name": "Steve",
  "age": 42,
  "description": null,
  "email1": "steve@example.com",
  "email2": null,
  "address1": {
    "type": "home",
    "shippingMethod": "Charge by quantity",
    "street": "Sunrise Ave",
    "streetNo": 17
     },
   "address2": {
    "type": "office",
    "shippingMethod": null,
    "street": "Sunset Ave",
    "streetNo": 71
     },
   "anotherField": "another value"
   },
   {
   "name": "Johnny",
   ...
   "anotherField": "some other value"
   }
]  

I can see that I need to wrap it up with an array of Client objects, because my JSON starts with a "[" and I can also see I need another container class for the inner fields address1 and address2. This is the container I came up with:

public class Client {
  String name;
  int age;
  String description;
  String email1;
  String email2;
  ClientAddress address1;
  ClientAddress address2;
  String anotherfield;
  ..
  getters() and setters()

  public class ClientAddress {
    String type;
    String shippingMethod;
    String street;
    int streetNo;
    ..
    getters() and setters()
  }
}

The instruction I wrote to grab the data and populate the wrapper fields is:

Client[] clientsArray= (new Gson()).fromJson(jsonClients, Client[].class);

The result is only partially satisfying; I managed to access all the primitive fields (such as name,email1..), but the address1 and address2 fields are both null. As a result,

clientsArray[i].getAddress1().getShippingMethod();

returns a null String.

Where did I go wrong?
Is there a particular way of creating the classes that I am missing?

Note: My JSON object is perfectly valid from a structure standpoint of view. If you see any errors, it's probably because they slipped when I was manually creating the above dummy/demo.

Just to follow GSON Collections good practices , try changing

 Client[] clientsArray= (new Gson()).fromJson(jsonClients, Client[].class);

to

 Type collectionType = new TypeToken<List<Client>>(){}.getType();
 List<Client> clientsArray = (new Gson()).fromJson(jsonClients, collectionType);

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