【问题标题】:How to parse json in flutter with arrays of arrays?如何用数组数组解析json?
【发布时间】:2019-09-30 11:02:55
【问题描述】:

如何使用颤振解析包含数组值数组的 json。我知道这个 json 格式是无效的,但不幸的是我需要解析它。

   {
   ModuleEId: [
   [
   "Test Equipment - R&D",
   "GPU_0001_180 KVA Dual AC 28.5V DC"
   ],
   [
   "Test Equipment - Electronics",
   "GPU_0004_180 KVA Dual AC 28.5 V DC"
   ]
   ]
   }

【问题讨论】:

  • 无效吗? ((((jsonDecode(string)['ModuleId'] as List)[0] as List)[0]) as String) == "Test Equipment - R&D"

标签: android ios flutter dart


【解决方案1】:

要解析 json,您可以使用包 dart:convert 中的 json.decode(jsonString)。但首先,您需要修复格式。

在这种情况下,您可以使用例如replaceAll 方法来添加双引号。

String jsonString = "/*loaded json*/";
jsonString = jsonString.replaceAll('ModuleEId', '"ModuleEId"');

然后

final parsed = json.decode(jsonString);

完整示例:Dartpad

【讨论】:

  • 它按预期工作。谢谢。您能说一下如何将其映射到自定义模型类吗?
  • @DayaNithi 我不知道您的自定义模型应该是什么样子。也许这会有所帮助:Serializing JSON inside model classes.
【解决方案2】:

它不是有效的 JSON,但它看起来像有效的 YAML。你可以利用它。 使用yaml 包:https://pub.dev/packages/yaml。然后将其转换为 JSON。

    String input = """
    {
     ModuleEId:
     [
       [
         "Test Equipment - R&D",
         "GPU_0001_180 KVA Dual AC 28.5V DC"
       ],
       [
         "Test Equipment - Electronics",
         "GPU_0004_180 KVA Dual AC 28.5 V DC"
       ]
     ]
    }
    """;
    var yamlDoc = loadYaml(input);
    final json = jsonEncode(yamlDoc);
    print(((((jsonDecode(json)['ModuleEId'] as List)[0] as List)[0]) as String));

【讨论】:

  • 抛出错误 [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理异常:类型 '_InternalLinkedHashMap' 不是类型 'String' 的子类型跨度>
  • 我们在谈论相同的输入字符串吗?您可以复制粘贴上面的代码并尝试吗?它适用于我的系统:-)
  • 没有。其实我在手机上试过。上面的答案很有效,谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 2015-09-15
相关资源
最近更新 更多