0
  • 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('<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);
}
  • 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,
    );
  }
}
1
  • 2
    Seems like you're not accessing the 'feeling_percentage' key at all. Commented May 27, 2022 at 12:57

5 Answers 5

1

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}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

This will fix your issue.

Comments

0

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))

2 Comments

after using json.decode() i am getting error as Exception has occurred. _TypeError (type 'Null' is not a subtype of type 'String') but response.body() is printing the data
It seems like one of the values you are getting from your json and trying to convert into your object may be null. You may have to review your data and do validations for nulls.
0

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

2 Comments

Error at happy: json["happy"] as String, as _CastError (type 'Null' is not a subtype of type 'String' in type cast)
JSON field names seem to have the first letter as capital: "Happy" instead of "happy".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.