- I have the below json data, wherein I want to access the values inside the
feeling_percentage
.
{
"status": "200",
"data": {
"feeling_percentage": {
"Happy": "0",
"Sad": "0",
"Energetic": "0",
"Calm": "0",
"Angry": "0",
"Bored": "0"
},
}
}
- I am able to fetch it using the below API code
Future<List<Data>> makePostRequest() async {
List<Data> list = [];
final uri = Uri.parse('https://www.qubehealth.com/qube_services/api/testservice/getListOfUserFeeling');
final headers = {'Content-Type': 'application/json', 'X-Api-Key':'<api_key>'};
Map<String, dynamic> body = {'user_id': 3206161992, 'feeling_date': '15-04-2022'};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
Response response = await post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
);
int statusCode = response.statusCode;
String responseBody = response.body;
print('response body' responseBody);
}
- After reading few articles, still not able to figure out how do I access the percentage of happy, sad inside the feeling_percentage.
- I have created the model as
class Data{
FeelingPercentage feelingPercentage;
Data(
{required this.feelingPercentage});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
feelingPercentage: FeelingPercentage.fromJson(json["data"]),
);
}
}
class FeelingPercentage {
String? happy;
String? sad;
String? energetic;
String? calm;
String? angry;
String? bored;
FeelingPercentage({this.happy, this.sad, this.energetic, this.calm, this.angry, this.bored});
factory FeelingPercentage.fromJson(Map<String, dynamic> json) {
return FeelingPercentage(
happy: json["happy"] as String,
sad: json["sad"] as String,
energetic: json["energetic"] as String,
calm: json["calm"] as String,
angry: json["angry"] as String,
bored: json["bored"] as String,
);
}
}
CodePudding user response:
Change this line in your model feelingPercentage: FeelingPercentage.fromJson(json["data"]),
to feelingPercentage: FeelingPercentage.fromJson(json["data"]["feeling_percentage"]),
This will fix your issue.
CodePudding user response:
You can use this website to convert your JSON object to a dart class. it automatically creates the fromJson function, which can be used to pass JSON and receive the Dart objects.