0

Let's assume we have JSON object like this:

{
 "employees" : {
        "Mike" : 23,
        "Bill" : 42,
        "Jimmy" : 30
    }
}

And the next classes:

public class Employees {

    private List<Employee> employees;
}


public class Employee {

    private String name;
    private int age;
}

Have we any ways to deserialize the json to Employees type object?

John Smith
  • 605
  • 4
  • 14
  • 2
    possible duplicate of [Google Gson - deserialize list object? (generic type)](http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type) – vidstige Feb 03 '15 at 09:49
  • Refer to this tutorial : http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ Also, the `employees` in your JSON has to be an array of objects. – Pramod Karandikar Feb 03 '15 at 09:50

2 Answers2

1

List can be used to deserialize array of elements [...] but {...} is object. If you want you can consider using Map instead of List

class Data {
    Map<String,String> employees;
}

...
Gson gson = new Gson();
Data data = gson.fromJson(json, Data.class);
for (Map.Entry<String, String> emp: data.employees.entrySet())
    System.out.println(emp.getKey()+" -> "+emp.getValue());

Output:

Mike -> 23
Bill -> 42
Jimmy -> 30

If you would like to parse your json using these classes

public class Employees {
    private List<Employee> employees;
}


public class Employee {
    private String name;
    private int age;
}

Your data should look like:

{
    "employees" : [
        {"name":"Mike", "age": 23},
        {"name":"Bill", "age": 42},
        {"name":"Jimmy", "age": 30}
    ]
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Yes, you're right, I know about correct json, but i hoped I can resolve this problem and link this json with that class. Thank you for help. – John Smith Feb 03 '15 at 17:20
0

You can use Jackson's ObjectMapper class to deserialize JSON like so: https://stackoverflow.com/a/6349488/2413303

Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428