Eugene
Eugene

Reputation: 60184

Class's fields initialization from JSON using Gson

I'm trying to use Gson to initialize my fields, but no success.

String complex = "{'menu': { 'id': 'file', 'value': 'File', 'popup': { 'task':
  [ {'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]
}}}";

Trying to do that with:

TasksHolder th = gson.fromJson(complex, TasksHolder.class);

TaskHolder class:

public class TasksHolder {

    List<Task> task;

    public TasksHolder() {
        task = new ArrayList<Task>();
    }
}

Please advice what can be done to make task of TaskHolder to be filled.

Upvotes: 1

Views: 3391

Answers (2)

StaxMan
StaxMan

Reputation: 116522

Your JSON does not map to class you define: it is missing couple of levels (main-level object that has 'menu' property, then menu object that actually contains TaskHolder. So you should either define class structure that JSON maps to (how else would Gson know what to map where?), or pre-process JSON to remove stuff you don't need.

Type-erasure mentioned by the other answer should NOT be the problem here: your 'task' property is declared as List, and that should be enough for Gson to determine generic type. Yes, field declarations do retain generic type information; type erasure has more to do with runtime information available via Class. So while type reference objects are needed for root types, they are not needed for properties under root properties.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298988

The problem is Generic Type Erasure. GSON has no idea, what kinds of objects to create because your class contains only a List (type information regarding Task is lost).

Here's how to deal with this problem in GSON:

Type listType = new TypeToken<List<Task>>() {}.getType();
List<Task> tasks = gson.fromJson(myTasks, listType);

But that won't help you, since you want the parent object, not just the list. I'm afraid you will have to write your own Custom Serialization and Deserialization methods

Upvotes: 3

Related Questions