2
votes

I have read the previously asked questions but none of them helped me.

My class is:

Class A{
String name;
JSONArray phone;
.....
}

I am using Rest client to send request and request is like:

{"name":"abc","phone":[{"no":"1234","type":"landline"},{"no":"4321","type","office"}]}

Now schema of this request is valid but when I send request my application throws an exception like:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

I am mapping request to class as:

           Gson gson=new Gson();
           A para = null;
            try{
                para = gson.fromJson(json, A.class);

            }catch(Exception e){
                e.printStackTrace();
                return false;
            }

Could someone explain that why my array in the request is not getting mapped with the array in class A?

1

1 Answers

2
votes

The Json Array object for the Gson library is "JsonArray" not "JSONArray", but the real problem is that you are telling it to parse a string from JSON to a JSON object, instead of your own internal object,

try this:

class Phone
{
    String no, type;
}

class A
{    
    String name;
    List<Phone> phone;  //or Phone[] phone;
}

also the last phonenumber in the list has a bug in the json:

{"no":"4321","type","office"}

should be:

{"no":"4321","type":"office"}