如何将数组解析为多项选择 QNA 颤振

时间:2021-05-07 07:07:12

标签: arrays json flutter array-map

我有一些来自 API 的数据

{
    "status": 200,
    "id": "1",
    "pertanyaan": "Berapa Penghasilan Anda",
    "type": "radio_opt",
    "opsi": "[\"1 juta\",\"2 Juta\",\"3 Juta\",\"4 Juta\",\"> 4 Juta\"]",
    "urutan": "3"
}

如何将此数组解析为 Map ? 任何人请帮助我:

我的代码:

Map<String, bool> values = {
    'foo': true,
    'bar': false,
  };


if(question.type == "check_opt"){
          // choices = jsonEncode(question.opsi) as List<List<String>>;
          // choices = question.opsi as List<List<String>>;
          values = question.opsi as Map<String, bool>;
        }else if (question.type == "radio_opt"){
          // values = question.opsi as Map<String, dynamic>;
          multi = jsonEncode(question.opsi);
        }

to this

1 个答案:

答案 0 :(得分:0)

不清楚哪些选项应该是真的 - 我下面的代码测试前缀 ">"

import 'dart:convert';

main(List<String> args) {
  String data = '''{
    "status": 200,
    "id": "1",
    "pertanyaan": "Berapa Penghasilan Anda",
    "type": "radio_opt",
    "opsi": "[\\"1 juta\\",\\"2 Juta\\",\\"3 Juta\\",\\"4 Juta\\",\\"> 4 Juta\\"]",
    "urutan": "3"
}''';
  Map<String, dynamic> question = json.decode(data);
  if (question["type"] == "radio_opt") {
    var opts = json.decode(question["opsi"]);
    Map<String, bool> map = {for (var opt in opts) opt: opt[0] == '>'};
    print(map);
  }
}

输出:

{1 juta: false, 2 Juta: false, 3 Juta: false, 4 Juta: false, > 4 Juta: true}