【问题标题】:How to handle dynamic json in flutter?如何在flutter中处理动态json?
【发布时间】:2021-04-25 01:28:14
【问题描述】:
    {
       "status": "error",
        "msg": "Please fill all the fields",
       "error": {
             "device_token": [
                     "The device token field is required.",
            ]
             "mobile_number": [
                     "The mobile number field is required."
            ]
        }
    }

这是我的 json 响应。由于错误对象是动态的,我该如何处理我的错误

【问题讨论】:

  • 您发送的 json 无效,您的意思是 device_token 或 mobile_numer 将存在,还是它们之间缺少逗号?

标签: json flutter dart


【解决方案1】:

我使用json_seializable。这是解决这个问题的好方法。 只是为了用装饰器标记你的模型并自动生成每个方法。顺便说一句,这是在flutter documentation 上推荐的。 此外,为变量添加类型并使用 Dart 编译器的强大功能也非常重要

【讨论】:

    【解决方案2】:

    我建议阅读 Flutter 文档中的 JSON and Serialization

    【讨论】:

      【解决方案3】:

      将您的 JSON 内容保存在一个变量中并按以下方式访问您的数据。
      另外,不要忘记“device_token”键后的逗号“,”

      var res = {
        "status": "error",
        "msg": "Please fill all the fields",
        "error": {
          "device_token": [
            "The device token field is required."
          ],
          "mobile_number": [
            "The mobile number field is required."
          ]
        }
      };
      
      var deviceToken = (res["error"] as Map)["device_token"].first;
      var mobileNumber = (res["error"] as Map)["mobile_number"].first;
      
      print(deviceToken);
      print(mobileNumber);
      

      【讨论】:

        猜你喜欢
        • 2014-08-08
        • 1970-01-01
        • 2017-05-25
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 2021-12-19
        • 2022-08-18
        • 1970-01-01
        相关资源
        最近更新 更多