【问题标题】:Mapping a model from JSON give me a error when map int value当映射 int 值时,从 JSON 映射模型给我一个错误
【发布时间】:2019-02-05 06:09:55
【问题描述】:

嗨,我试图从 JSOn 获取值,但是当我映射一个 INT 值时,颤动显示该错误并且没有返回数据:

flutter: type 'String' is not a subtype of type 'int'

这是我的模型:

import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';


class Kits {

  final String country;
  final String franchise;
  final String type;
   String brand;
   String procedure;
   String setdesc;
   int traymaterialid;
   String traydesc;
   int referencia;
   String descart;
   int cantidad;
   int homologado;
   int bajopresu;
   DateTime insdate;


   Kits(this.country,this.franchise,this.type, this.brand, this.procedure,this.traydesc, this.traymaterialid);

  factory Kits.fromJson(Map<String, dynamic>  json) {
         return Kits(json['COUNTRY'], json['FRANCHISE'], json['TYPE'], json['BRAND'], json['PROCEDURE'], json['TRAYDESCRIPTION'], json['TRAYMATERIALID'] /* <-- INT*/ );
  }

}

class KitsData {

  static const url = 'http://app-smith.com/en/kits_API.php?email=miquel@winfor.es&macid=888&passwd=Wcz95f4UGkax5G';
  final JsonDecoder _decoder = new JsonDecoder();

    Future<List<Kits>> fetch(){    
  return http.get(url).then((http.Response response){
    final String jsonBody = response.body;
    //final statusCode = response.statusCode;

      /*if (statusCode < 200 || statusCode >= 300 || jsonBody == null){ 
        return List();
      }*/

      final kitsContainer = _decoder.convert(jsonBody);
      final List kitsItems = kitsContainer['kits'];

      return kitsItems.map( (kitsRaw) => new Kits.fromJson(kitsRaw) ).toList();

    });

  } 

}

class FetchDataException implements Exception {
  String _message;

  FetchDataException(this._message);

  String toString() {
    return "Exception: $_message";
  }
}

我不明白为什么会这样,因为 fromJson 只获取我传递密钥的值,然后在我的列表中我将值转换为字符串。

JSON 片段:

{"kits": [{"COUNTRY":"FR","FRANCHISE":"KNEE","TYPE":"LEGION","BRAND":"REVISION","PROCEDURE":"LEGION REVISION","SETDESCRIPTION":"LEGION REVISION - INSTRUMENTS","TRAYMATERIALID":"551820141LRC","TRAYDESCRIPTION":"INSTR LEGION REVISION","REFERENCIA":"71431722","DESCRIPCIONARTICULO":"LGN SCW LWDG TRL S3 5D X 10P","CANTIDAD":"1","HOMOLOGADO":"","BAJOPRESUPUESTO":"","INS_DATE":"2018-08-23 18:57:04"}

【问题讨论】:

  • 它很可能 不是 一个 int 值。确保该值不包含在 JSON 字符串中的 "" 中。
  • 我的答案中添加了 JSON
  • 所有数值都包含在引号内,因此它们不会以int 的形式传输,而是以String 的形式传输

标签: json dart flutter


【解决方案1】:

所有数值都包含在引号内,因此它们不会作为int 而是作为String 传输。错误信息是正确的。如果您希望它们为String,请确保不引用这些值,如果您不控制使用int.parse() 将它们从String 转换为int

【讨论】:

  • 还要注意TRAYMATERIALID 的值是"551820141LRC",它包含字母和数字。它不是整数,int.parse 也不会将其解析为整数。
  • 我明白了。我错过了代码中的评论。我看到了"REFERENCIA":"71431722",但我找不到没有引号的带有数值的单个字段。
猜你喜欢
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多