Lav Sharma
Lav Sharma

Reputation: 339

How to access JSON nested data in flutter dart

{
    "status": "200",
    "data": {
        "feeling_percentage": {
            "Happy": "0",
            "Sad": "0",
            "Energetic": "0",
            "Calm": "0",
            "Angry": "0",
            "Bored": "0"
        },
    }
}
Future<List<Data>> makePostRequest() async {
  List<Data> list = [];
  final uri = Uri.parse('<api>');
  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);
}
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,
    );
  }
}

Upvotes: 0

Views: 745

Answers (5)

user18309290
user18309290

Reputation: 8380

First decode response.body, then create FeelingPercentage object from json["data"]["feeling_percentage"] map.

Future<FeelingPercentage> makePostRequest() async {
...
  final json = json.decode(response.body);
  return FeelingPercentage.fromJson(json["data"]["feeling_percentage"])
}

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,
    );
  }
}

Upvotes: 0

mezoni
mezoni

Reputation: 11220

Another way:

import 'package:fast_json/fast_json_selector.dart' as parser;

void main() {
  final path = '{}.data.{}.feeling_percentage';
  final level = path.split('.').length;
  void select(parser.JsonSelectorEvent event) {
    final levels = event.levels;
    if (levels.length == level && levels.join('.') == path) {
      print(event.lastValue);
      event.lastValue = null;
    }
  }

  parser.parse(_source, select: select);
}

const _source = '''
{
    "status": "200",
    "data": {
        "feeling_percentage": {
            "Happy": "0",
            "Sad": "0",
            "Energetic": "0",
            "Calm": "0",
            "Angry": "0",
            "Bored": "0"
        }
    }
}''';

Output:

{Happy: 0, Sad: 0, Energetic: 0, Calm: 0, Angry: 0, Bored: 0}

Upvotes: 1

J. S.
J. S.

Reputation: 9635

You can do a JSON decode that will will result in a map, and then do the assigned like you are doing on your from Json factory, but as another constructor instead:

Class

Todo.fromMap(Map map) :
    this.title = map['title'],
    this.completed = map['completed'];

In use

Todo.fromMap(json.decode(item))

Upvotes: 0

Ali Bakhtiyari
Ali Bakhtiyari

Reputation: 332

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.

Upvotes: 1

Shahzad Umar Baig
Shahzad Umar Baig

Reputation: 172

Change this line in your model feelingPercentage: FeelingPercentage.fromJson(json["data"]), to feelingPercentage: FeelingPercentage.fromJson(json["data"]["feeling_percentage"]),

This will fix your issue.

Upvotes: 0

Related Questions