methuselah :
I am getting the following JSON output:
{
"range": "Frontpage!E6:E15",
"majorDimension": "ROWS",
"values": [
[
"FundRequest"
],
[
"nOS"
],
[
"NEX"
],
[
"DREP"
],
[
"ChromaWay"
],
[
"Jura"
],
[
"Origo"
],
[
"Phantasma"
],
[
"NuCypher"
],
[
"Oasis Labs"
]
]
}
So I created the following wrapper:
public class Wrapper {
private String range;
private String majorDimension;
private List<String> values;
// getters and setters
}
Now I want use GsonBuilder
to map the JSON to my object:
Gson gson = new GsonBuilder().create();
Wrapper w = gson.fromJson(jsonString, Wrapper.class);
but I get the following error:
java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 37 path $.values[0]
How do I fix it? Is there any way for me to convert it from a List<List<String>>
to a List<String>
?
VelNaga :
First, You should use List List<<List<String>>
instead of List<String>
for values.
second, You can get List<String>
from List<List<String>>
Using below code,
public <T> List<T> flattenListOfListsImperatively(
List<List<T>> nestedList) {
List<T> ls = new ArrayList<>();
nestedList.forEach(ls::addAll);
return ls;
}
or using Java-8
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
Also, do a search in GSON is there any built-in way to flatten the nested collection. Please post it here if there is anything.
Edit 1: I did a quick search in GSON library and it seems possible.You have write an adapter to achieve the things. Please refer this link link2