Issue
I'm trying to deserialize a nested array from a JSON response. It's the first time I've ever gotten an array of arrays and I'm not quite sure how to structure my class to handle it.
{
"prices": [
[
1641670404234,
0.01582586939240936
],
[
1641674037525,
0.015999047707867396
],
[
1641677655158,
0.016072905257982606
]
...
],
}
If the brackets were { instead of [
{
"prices": {
{
1641670404234,
0.01582586939240936
},
{
1641674037525,
0.015999047707867396
},
{
1641677655158,
0.016072905257982606
}
}
...
}
I could use
@SerializedName("prices")
private List<Price> prices;
public class Price {
private long date;
private BigDecimal price;
}
However since it is [ instead, I am quite unsure how to structure it.
I've tried adding another List wrapper to it but that throws an error
@SerializedName("prices")
private List<List<Price>> prices;
IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 26 path $.prices[0][0]
I've also tried wrapping it with a JSONArray
@SerializedName("prices")
private List<JSONArray<Price>> prices;
but that's not quite right
I've tried searching other SO answers but I could not find any examples where it's two consecutive [ [ brackets.
They are all { [ or [ {.
What's the correct way to do it?
Solution
Assuming this is the correct JSON:
{
"prices": [
[
1641670404234,
0.01582586939240936
],
[
1641674037525,
0.015999047707867396
],
[
1641677655158,
0.016072905257982606
]
]
}
Then you can use this model to deserialize data to:
JAVA:
public class PricesModel {
public ArrayList<ArrayList<Double>> prices;
}
KOTLIN:
data class PricesModel (
@SerializedName("prices" ) var prices : ArrayList<ArrayList<Double>> = arrayListOf()
)
Handy JSON converters to Java and Kotlin.
Answered By - Sergey

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.