Issue
An API is giving me a JSON response like so :
{
"amountCredited":0,
"isFirstOrder":false,
"orderItems":[
{
"_id":624342e1c66be9001d501230,
"status":2,
"pinCode":749326,
"kioskId":61bb3982089a66001db4ab77,
"kioskActivityId":620668ad433322b99557c874
}
]
}
I'm trying to access the data inside the "orderItems"
in order to feed it to an existing parsing model in the App
order = OrderItemModel.fromJson(response.body['orderItems'] as Map<String, dynamic>);
but since the data inside orderItems
JSON response is inside an array I can't access it this way..
How can I access it knowing that this JSON "orderItems"
array will always only have one item as a response ?
Would something like response.body['orderItems' : [0]]
enable me to access the first item data ?
Solution
Since you always know that the array will always have only one item. We'll first make it a List & then access the first element.
order = OrderItemModel.fromJson((response.body['orderItems'] as List<dynamic>).first as Map<String, dynamic>);
To understand it a bit better refer to the code below:
The JSON response contains an array, which we need to access.
final ordersArray = response.body['orderItems'] as List<dynamic>;
Then we want to access the first order (according to the question)
final firstOrder = ordersArray.first as Map<String, dynamic>;
Once we have the order, we'll convert it to the model
final order = OrderItemModel.fromJson(firstOrder);
EDIT:
as it was pointed out in a comment List objects have a getter called first
which can be used to get the first element, the code has been updated with that.
Answered By - Advait
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.