簡體   English   中英

如何在flutter dart中訪問JSON嵌套數據

[英]How to access JSON nested data in flutter dart

  • 我有以下 json 數據,其中我想訪問feeling_percentage中的值。
{
    "status": "200",
    "data": {
        "feeling_percentage": {
            "Happy": "0",
            "Sad": "0",
            "Energetic": "0",
            "Calm": "0",
            "Angry": "0",
            "Bored": "0"
        },
    }
}
  • 我可以使用下面的 API 代碼來獲取它
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);
}
  • 在閱讀了幾篇文章之后,仍然無法弄清楚我如何訪問feeling_percentage 中的快樂、悲傷的百分比。
  • 我已將模型創建為
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,
    );
  }
}

您可以使用網站將您的 JSON 對象轉換為 dart 類。 它會自動創建 fromJson 函數,該函數可用於傳遞 JSON 並接收 Dart 對象。

將模型中的這一行更改feelingPercentage: FeelingPercentage.fromJson(json["data"]), to feelingPercentage: FeelingPercentage.fromJson(json["data"]["feeling_percentage"]),

這將解決您的問題。

您可以執行將生成地圖的 JSON 解碼,然后像在from Json工廠中所做的那樣進行分配,但作為另一個構造函數:

班級

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

正在使用

Todo.fromMap(json.decode(item))

首先解碼response.body ,然后從json["data"]["feeling_percentage"]映射創建FeelingPercentage對象。

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

另一種方式:

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"
        }
    }
}''';

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM