-1

I got JSON like

{
"items":[
{
"id":15
,"name":"abc"
}
,{
"id":16
,"name":"xyz%"
}
,{
"id":17
,"name":"qwerty"
}
,{
"id":18
,"name":"rudloph"
}
,{
"id":19
,"name":"jane"
}
,{
"id":20
,"name":"doe"
}
]
}

I have class which is like:

public class Foo {
    public String id;    
    public String name;
}

And I want to convert this JSON into List<Foo>. How can i do this? Right now I am doing like:

List<Foo> fooList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(json);
JSONArray araray = jsonObject.getJSONArray("items");
for(int i =0 ; i < araray.length();i++){
    Foo dto = new Foo();
    dto.setId(Long.valueOf((String) araray.getJSONObject(i).get("id")));
    dto.setName((String) araray.getJSONObject(i).get("name"));
    fooList.add(dto);
}

PS: Cannot change JSON. Jackson or Gson. Please let me know with code example.

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105

4 Answers4

0

i think you need to use the java json api and you need bind it manually

friend
  • 15
  • 1
  • 11
  • I am doing something like this List fooList = new ArrayList<>(); JSONObject jsonObject = new JSONObject(json); JSONArray araray = jsonObject.getJSONArray("items"); for(int i =0 ; i < araray.length();i++){ Foo dto = new Foo(); dto.setId(Long.valueOf((String) araray.getJSONObject(i).get("id"))); dto.setName((String) araray.getJSONObject(i).get("name")); fooList.add(dto); } Is there any better way – vaibhav srivastava May 23 '17 at 05:16
  • you need to use jakson- jason api that work like jax b – friend May 23 '17 at 06:05
  • in rest api rest implementation it internally used jakson-son you no need to manage – friend May 23 '17 at 06:06
0

If you use gson, you may use TypeToken to load the json string into a custom Foo object.

List<Foo> objects = gson.fromJson(source, new TypeToken<List<Foo>>(){}.getType());

source can be String or BufferedReader.

Jay Smith
  • 2,331
  • 3
  • 16
  • 27
0

You are having the wrong model for the JSON String. actually the list of Foo is inside another Model. Simply write another class like

public class Item {

    List<Foo> items;

    public Item() {
    }

   // getter setter
}

Now you can use com.fasterxml.jackson.databind.ObjectMapper like this

ObjectMapper mapper = new ObjectMapper();
Item item = mapper.readValue(json, Item.class);

for(Foo foo : item.getItems()) {
            ...
}
Shafin Mahmud
  • 3,831
  • 1
  • 23
  • 35
0

Try this with GSON.

Gson gson = new Gson();
Map<String, List<Foo>> objects = gson.fromJson(source,
    new TypeToken<Map<String, List<Foo>>>(){}.getType());
List<Foo> list = objects.get("items");