Question

I am trying to deserialize the following JSON:

[{
    "customerDetails":
          {
            "customer_name": "name",
            "customer_email": "email"
          },
    "shippingD‌​etails":
          {
            "shipping_contact": "name",
            "shipping_street": "Av:"
          }
}] 
Array
 (
    [0] => Array
            (
               [customerDetails] => Array
            (
                [customer_name] => name
                [customer_email] => email             
            )
        [shippingDetails] => Array
            (
                [shipping_contact] => shipname
                [shipping_street] => Av:Name                 
            )
   )
)

Heres my classes:

public class Order {
    private List<CustomerDetail> customerDetail;
    private List<Shipping> shipping;
    //getters and setters
}
public class Shipping {
    private String contact;
    private String street;
    //getters and setters
}
public class CustomerDetail{
    private String name;
    private String email;
    //getters and setters
}

I tried this:

Gson g = new Gson();        
Order[] order = g.fromJson(new FileReader("jason"), Order[].class);
List <CustomerDetail> cd = order[0].getCustomerDetail();
System.out.println(cd.get(0).getName());

But I keep gettin either NullPointer or

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
Was it helpful?

Solution

You Java doesn't match the JSON, and the error message is telling you that you're trying to parse an object rather than an array (although, the code you show using Gson wouldn't throw the exception). I'm also not sure what the thing you show under your JSON is, because it bears no resemblance to the JSON either.

Your JSON is an array. That array contains an object (presumably you're expecting it to have many of these, but as-is it shows one). That object has two fields; customerDetails and shippingD‌​etails that each hold another object.

Your Orders class would need to be:

public class Orders {
    private CustomerDetail customerDetails;
    private Shipping shippingDetails;
}

(and given that it looks like that's a single order, I'd drop the plural and name the class Order)

You can then parse that JSON with Gson via:

Orders[] orders = new Gson().fromJson(myJson, Orders[].class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top