Is it possible to parse a JSON response to POJO, even though the response only sends back Rows and Columns?
I get this response from an API:
{
"rows": [
[
"FIRST NATIONAL BANK OF OMAHA",
36644,
"COM",
44527,
198809,
"SH",
-1.5631,
"Put",
"2019-09-30"
],
[
"WAYNE HUMMER INVESTMENTS L.L.C.",
49096,
"COM",
17975,
90817,
"SH",
2.8971,
"Put",
"2019-06-30"
]
],
"columns": [
"Institution Name",
"Institution CIK",
"Class of Security Held",
"Value of Security Held",
"Volume of Security Held",
"Type of Security Held",
"Quarterly Change in Security Held",
"Put/Call",
"Report Date"
]
}
This is the code I am using, shortened for brevity, to connect to the API and get the JSON response which I pass through deserializer class using Gson:
public static void requestResponse(){
URL apiURL = new URL("http://apilink.com/api/getSomething.json?T=gnbuweiogh9y89234y&symbol=GOOG");
String readLine = null;
HttpConnection apiConnection = (HttpConnection) apiURL.openConnection();
apiConnection.setRequestMethod("GET");
int responseCode = apiConnection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(apiConnection.getInputStream()));
StringBuffer response = new StringBuffer();
while((readLine = in.readLine()) != null) {
response.append(readLine);
}
in.close();
String jsonResponse = response.toString();
Deserializer deSerializer = new Gson().fromJson(jsonResponse, Deserializer .class);
List<String> columns = deSerializer.getColumns;
// Do something with the data
}
}
This is the deserialization class I made:
public class deSerializer {
@SerializedName("rows")
@Expose
private List<List<String>> rows = null;
@SerializedName("columns")
@Expose
private List<String> columns = null;
public List<List<String>> getRows() {
return rows;
}
public void setRows(List<List<String>> rows) {
this.rows = rows;
}
public List<String> getColumns() {
return columns;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
}
I was expecting the JSON response to be in this format which would have made the serialization simpler:
{
"data": [{
"Institution Name": "FIRST NATIONAL BANK OF OMAHA",
"Institution CIK": 36644,
"Class of Security Held": "COM",
"Value of Security Held": 44527
} ]
}
Sorry for the long post, but what would be the best approach to deserialize the response to POJO?
Thanks a lot.
You can convert it to the format you want by adding the following helper method to your deSerializer
class:
public List<Map<String, Object>> asListOfMaps() {
List<Map<String, Object>> list = new ArrayList<>(this.rows.size());
for (List<Object> data : this.rows) {
Map<String, Object> row = new LinkedHashMap<>(this.columns.size());
for (int i = 0; i < this.columns.size(); i++)
row.put(this.columns.get(i), data.get(i));
list.add(row);
}
return list;
}