Sandy
Sandy

Reputation: 323

Convert JSON to List<List<String>> in Java

I am having Json String this way,

json= [{"id":"1","label":"2","code":"3"},{"id":"4","label":"5","code":"6"}]

I tried converting it into Java Object this way, by using Gson,

and a Pojo called Item.java with fields namely id,label and code and getter setters for them.

String id;
    String label;
    String code;
    //getter setters

Gson gson = new Gson();
List<Item> items = gson.fromJson(json, new TypeToken<List<Item>>(){}.getType());

Then converted Java Object to List this way,

List<String> strings = new ArrayList<String>();
        for (Object object : items) {
            strings.add(object != null ? object.toString() : null);
}

My output is this way,

[Item [id=1, label=2, code=3], Item [id=6, label=5, code=6]

But i need it as List<List<String>> and without [Items] i.e,

[[id=1, label=2, code=3],[id=4, label=5, code=6]]

or direct 



List<List<String>>

without key.

[[1, 2, 3],[4, 5, 6]]

What is that I am missing? Can some body help me in this?

Upvotes: 4

Views: 3013

Answers (1)

azurefrog
azurefrog

Reputation: 10945

The code you already have posted gives you a List<Item>, so it sounds like you're just unsure how to build a List<List<String>> out of it.

What you're doing here:

for (Object object : items) {

is failing to take advantage of the fact that items is a List<Item>, not a List<Object>.

You can create an enhanced for-loop that pulls actual Items out like so:

for (Item item : items) {

This will let you properly access the data in them to build a sub-list:

    String json = "[{id:1,label:2,code:3},{id:4,label:5,code:6}]";
    List<Item> items = new Gson().fromJson(json, new TypeToken<List<Item>>(){}.getType());

    List<List<String>> listOfLists = new ArrayList<>();
    for (Item item : items) {
        List<String> subList = new ArrayList<>();
        subList.add(item.getId());
        subList.add(item.getLabel());
        subList.add(item.getCode());
        listOfLists.add(subList);
    }

    System.out.println(listOfLists);  // [[1, 2, 3], [4, 5, 6]]

However

If it's just that you don't like the output format of a List<Item>, a much simpler way to fix your code is to just override toString() in such a way that it prints what you need.

If I create the toString() method in Item to look like this:

public class Item {
    private String id;
    private String label;
    private String code;

    @Override
    public String toString() {
        return "[" + id + ", " + label + ", " + code + "]";
    }

    // getters, setters...
}

...then when I print a List<Item> it looks the way you want it:

    String json = "[{id:1,label:2,code:3},{id:4,label:5,code:6}]";
    List<Item> items = new Gson().fromJson(json, new TypeToken<List<Item>>(){}.getType());
    System.out.println(items);  // [[1, 2, 3], [4, 5, 6]]

Upvotes: 2

Related Questions