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

I have a Json String this way

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

I tried converting it to a Java object this way using Gson,

and Pojo called Item.java with fields, namely identifiers, labels and codes and getter settings 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 the Java object is converted to a list in such a way

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

My conclusion is this way

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

But I need this as List<List<String>>without [Items] ie,

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

or direct 



List<List<String>>

keyless.

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

What am I missing? Can someone help me with this?

+4
source share
1 answer

, , List<Item>, , , List<List<String>> .

:

for (Object object : items) {

, items List<Item>, a List<Object>.

for, Item :

for (Item item : items) {

:

    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]]

List<Item>, - toString() , , .

toString() Item, :

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

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

    // getters, setters...
}

... , List<Item>, , :

    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]]
+2

All Articles