Reputation: 315
I am trying to fetch the JSON data coming by the Http library. I would like to diplay only the "alert_description" value for the first object to user. How i can access to this attribut ?
My API respone :
{
"code": 0,
"message": " success",
"data": {
"data": {
"current_page": 1,
"data": [
{
"id": 62,
"user_id": 53,
"boxIdentifiant": 1924589682265245,
"boxName": "Box Sfax",
"alert_date": "2021-05-30",
"alert_time": "09:40",
"alert_description": "Panne Pression",
"alert_level": "warning"
},
{
"id": 61,
"user_id": 53,
"boxIdentifiant": 1924589682265243,
"boxName": "Box Tunis",
"alert_date": "2021-05-30",
"alert_time": "09:40",
"alert_description": "Panne Pression Roux",
"alert_level": "info"
},
{
"id": 58,
"user_id": 53,
"boxIdentifiant": 1924589682265244,
"boxName": "Box Office",
"alert_date": "2021-05-30",
"alert_time": "09:40",
"alert_description": "Panne Pression Roux",
"alert_level": "warning"
},
My code :
var response =
await http.get(Uri.parse(ApiUtil.GET_ALERT), headers: headers);
print("here================");
// print(response);
var data = json.decode(response.body);
print(data['data']['data']['data']);
if (data['status'] == 200) {
showNotification(data['message'], flp);
} else {
print("no message");
}
return Future.value(true);
});
}
Upvotes: 1
Views: 202
Reputation: 151
For decoding a JSON like this
{
"id":"xx888as88",
"timestamp":"2020-08-18 12:05:40",
"sensors":[
{
"name":"Gyroscope",
"values":[
{
"type":"X",
"value":-3.752716,
"unit":"r/s"
},
{
"type":"Y",
"value":1.369709,
"unit":"r/s"
},
{
"type":"Z",
"value":-13.085,
"unit":"r/s"
}
]
}
]
}
You can do this:
void setReceivedText(String text) {
Map<String, dynamic> jsonInput = jsonDecode(text);
_receivedText = 'ID: ' + jsonInput['id'] + '\n';
_receivedText += 'Date: ' +jsonInput['timestamp']+ '\n';
_receivedText += 'Device: ' +jsonInput['sensors'][0]['name'] + '\n';
_receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][0]['type'] + '\n';
_receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][0]['value'].toString() + '\n';
_receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][1]['type'] + '\n';
_receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][1]['value'].toString() + '\n';
_receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][2]['type'] + '\n';
_receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][2]['value'].toString();
_historyText = '\n' + _receivedText;
}
Upvotes: 0
Reputation: 5903
I dunno how Http library works, but in Dio library you don't need to do decode anything, it's pretty straight forward. See if this helps you:
var response = await Dio().post(yourUrl, data: { param1: value1, param2: value2 });
for (var item in response.data['data']['data']['data'])
{
print(item['alert_description']);
}
Since you're using the GET
method, use Dio().get()
and queryParameters:
instead of Dio().post()
and data:
respectively.
Upvotes: 1