Paul Stanley
Paul Stanley

Reputation: 2161

Gson not deserialising ArrayList as expected

This is my Json string:

jsonString ="{"Extras":[{"Name":"TEST","Value":"23455676654"}],"CommandCode":1005}" 

This is my Class

public class ServerMsg {  
    int CommandCode;  
    public List<Extra> extras = new ArrayList<Extra>();  
}

When I code:

ServerMsg msg = new ServerMsg();  
Gson gSon = new Gson();
msg = gSon.fromJson(jsonString,Servermsg.class);  

I get no objects in the extras list.
What have I coded incorrectly?

Upvotes: 0

Views: 69

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

Change your JSON object with name Extras to extras

{"extras":[{"Name":"TEST","Value":"23455676654"}],"CommandCode":1005}

Or change the field name from extras to Extras.

public class ServerMsg {  
    int CommandCode;  
    public List<Extra> Extras = new ArrayList<Extra>();  
}

Gson, by default, uses your field names. They have to match the nested JSON object names.

You should use Java naming conventions and write your variable names with a leading lowercase character.

Upvotes: 1

Related Questions