What is the quickest way to parse this json array into a list?
[
["FundRequest"],
["nOS"],
["NEX"],
["DREP"],
["ChromaWay"],
["Jura"],
["Origo"],
["Phantasma"],
["NuCypher"],
["Oasis Labs"]
]
Its being generated from the following code:
private void getNames(String spreadsheetUrl) {
JSONObject json = readJsonFromUrl(spreadsheetUrl);
String result = json.get("values").toString();
log.debug("Found: {}", result);
}
The output is from the following json response:
{
"range": "Frontpage!E6:E15",
"majorDimension": "ROWS",
"values": [
[
"FundRequest"
],
[
"nOS"
],
[
"NEX"
],
[
"DREP"
],
[
"ChromaWay"
],
[
"Jura"
],
[
"Origo"
],
[
"Phantasma"
],
[
"NuCypher"
],
[
"Oasis Labs"
]
]
}
1 Answer 1
You could use a library like GSON:
Install it with maven:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
EDIT:
If you're trying to parse this:
{
"range": "Frontpage!E6:E15",
"majorDimension": "ROWS",
"values": [
[
"FundRequest"
],
[
"nOS"
],...
as a java object then create a wrapper class for your json entity:
public class Wrapper {
private String range;
private String majorDimension;
private List<?> values;
/**
* @return the range
*/
public String getRange() {
return range;
}
/**
* @return the values
*/
public List<?> getValues() {
return values;
}
/**
* @param values the values to set
*/
public void setValues(List<?> values) {
this.values = values;
}
/**
* @return the majorDimension
*/
public String getMajorDimension() {
return majorDimension;
}
/**
* @param majorDimension the majorDimension to set
*/
public void setMajorDimension(String majorDimension) {
this.majorDimension = majorDimension;
}
/**
* @param range the range to set
*/
public void setRange(String range) {
this.range = range;
}
}
Then using GSON you can parse a Json string into a wrapper object:
Gson gson = new GsonBuilder().create();
Wrapper w = gson.fromJson(jsonString, Wrapper.class);
Check this: http://www.javacreed.com/simple-gson-example/
EDIT:
If you're trying to parse this:
[
["FundRequest"],
["nOS"],
["NEX"],
["DREP"],
["ChromaWay"],
["Jura"],
["Origo"],
["Phantasma"],
["NuCypher"],
["Oasis Labs"]
]
As an array of arrays, then using gson you can do:
List<?> arr = gson.fromJson("[[\"FundRequest\"],[\"nOS\"],...]", List.class);
System.out.println(arr);
The println shall print: [[FundRequest], [nOS], ...]
The json array of arrays shall be parsed as a list of lists
Hope this helps
2 Comments
[ ["FundRequest"], ["nOS"], ...` or this: { "range": "Frontpage!E6:E15", "majorDimension": "ROWS", "values": [ FundRequest" ], ... ?
[ ["FundRequest"], ["nOS"], ["NEX"], ["DREP"], ["ChromaWay"], ["Jura"], ["Origo"], ["Phantasma"], ["NuCypher"], ["Oasis Labs"] ]