web-dev-qa-db-ja.com

Flutterで応答JSONをオブジェクトに変換する方法は?

成功のJSON文字列をオブジェクトに変換しようとしています。私は適切な方法でやっていないのかもしれませんが、JSONをオブジェクトに変換することに関していくつか質問があります。

また、ログでこの例外を取得しています。

NoSuchMethodError:クラス '_ InternalLinkedHashMap'には、一致する引数を持つインスタンスメソッド 'cast'がありません
受信者:_LinkedHashMap len:3 試行された呼び出し:cast>()

Q1。そのデータオブジェクトをモデルにもキャストする必要がありますか?
Q2。これは、JSONをオブジェクト(SignUpResponse)に変換するための最良かつ簡単な方法です。
Q3。シリアライゼーションで行う方が良いですか?

応答JSON:

{
    "data": {
        "_id": "5bd2a59f4c59de1ac517d7bf",
        "email": "[email protected]",
        "phoneNumber": "2417874147",
        "isAddressApproved": 0,
        "unitNumber": "144",
        "streetAddress": "sdfsddsf",
        "area": "asd",
        "zipCode": "112233",
        "totalOrder": 0,
        "todayOrder": 0,
        "isPauseDelivery": false,
        "vacationStartDt": null,
        "vacationEndDt": null,
        "defaultLiter": 1
    },
    "message": "New User Created",
    "error": false
}

オンラインツールによって作成されたSignUpResponse

  class SignUpResponse {
  Data data;
  String message;
  bool error;

  SignUpResponse({this.data, this.message, this.error});

  SignUpResponse.fromJson(Map<String, dynamic> json) {
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
    message = json['message'];
    error = json['error'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.data != null) {
      data['data'] = this.data.toJson();
    }
    data['message'] = this.message;
    data['error'] = this.error;
    return data;
  }
}

class Data {
  String sId;
  String email;
  String phoneNumber;
  int isAddressApproved;
  String unitNumber;
  String streetAddress;
  String area;
  String zipCode;
  int totalOrder;
  int todayOrder;
  bool isPauseDelivery;
  Null vacationStartDt;
  Null vacationEndDt;
  int defaultLiter;

  Data(
      {this.sId,
        this.email,
        this.phoneNumber,
        this.isAddressApproved,
        this.unitNumber,
        this.streetAddress,
        this.area,
        this.zipCode,
        this.totalOrder,
        this.todayOrder,
        this.isPauseDelivery,
        this.vacationStartDt,
        this.vacationEndDt,
        this.defaultLiter});

  Data.fromJson(Map<String, dynamic> json) {
    sId = json['_id'];
    email = json['email'];
    phoneNumber = json['phoneNumber'];
    isAddressApproved = json['isAddressApproved'];
    unitNumber = json['unitNumber'];
    streetAddress = json['streetAddress'];
    area = json['area'];
    zipCode = json['zipCode'];
    totalOrder = json['totalOrder'];
    todayOrder = json['todayOrder'];
    isPauseDelivery = json['isPauseDelivery'];
    vacationStartDt = json['vacationStartDt'];
    vacationEndDt = json['vacationEndDt'];
    defaultLiter = json['defaultLiter'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['_id'] = this.sId;
    data['email'] = this.email;
    data['phoneNumber'] = this.phoneNumber;
    data['isAddressApproved'] = this.isAddressApproved;
    data['unitNumber'] = this.unitNumber;
    data['streetAddress'] = this.streetAddress;
    data['area'] = this.area;
    data['zipCode'] = this.zipCode;
    data['totalOrder'] = this.totalOrder;
    data['todayOrder'] = this.todayOrder;
    data['isPauseDelivery'] = this.isPauseDelivery;
    data['vacationStartDt'] = this.vacationStartDt;
    data['vacationEndDt'] = this.vacationEndDt;
    data['defaultLiter'] = this.defaultLiter;
    return data;
  }
}

Calling REST POST API

void postCallSignUp(BuildContext context, var body) {
// This Function will check Internet is available or not.
Utils.checkConnection().then((connectionResult) {
  if (connectionResult) {
    http.post(Constants.BASE_URL + Constants.CREATE_USER,
        body: body,
        headers: {
          "Accept": "application/json",
          "content-type": "application/json"
        }).then((http.Response response) {
      final String res = response.body;
      final int statusCode = response.statusCode;

      if (statusCode < 200 || statusCode > 400 || json == null) {
        _onFailureResponse(new Exception("Error while fetching data"));
      } else {
        //Parsing json response to particular Object.
        print(json.decode(res));

        // Unable to cast json here...
        final parsed = json.decode(res).cast<Map<String, dynamic>>();
        parsed.map<SignUpResponse>((json) => SignUpResponse.fromJson(json));
        SignUpResponse signUpResponse = parsed.map<SignUpResponse>((json) => SignUpResponse.fromJson(json));
        _onSuccessResponse(signUpResponse);
      }
    });
  } else {
    _onNoInternetConnection();
    Utils.showAlert(context, "Alert", "Internet is not connected.", () {
      Navigator.pop(context);
    });
  }
});
}

ここで何が起こっているのか理解できませんか? jsonを特定のオブジェクトに変換するために、なぜそんなに多くのことをしなければならないのですか?

10
Harsh Bhavsar

キャストを使用する必要はありません。マップに直接解析できます

final Map parsed = json.decode(res); 

マップを作成したら、そのデータを使用してオブジェクトに変換できます。

final signUp = SignUpResponse.fromJson(parsed);

オブジェクトの配列を解析する場合は、次のようにすることができます。

//assuming this json returns an array of signupresponse objects
final List parsedList = json.decode(res); 

List<SignUpResponse> list = parsedList.map((val) =>  SignUpResponse.fromJson(val)).toList();
12
diegoveloper

JSON:

    [
     {
       "id":1,
       "name":"Afghanistan",
       "iso3":"AFG",
       "iso2":"AF",
       "phone_code":"93",
       "capital":"Kabul",
       "currency":"AFN"
     },
     {
       "id":2,
       "name":"Aland Islands",
       "iso3":"ALA",
       "iso2":"AX",
       "phone_code":"+358-18",
       "capital":"Mariehamn",
       "currency":"EUR"
       },
    ]

POJOクラス:

    class country{
       String id;
       String name;
       String currency;

       country({this.id,this.name,this.currency});

       factory country.fromJson(Map<String, dynamic> parsedJson){
         return country(
         id: parsedJson['id'].toString(),
         name : parsedJson['name'].toString(),
         currency: parsedJson['currency'].toString() 
         );
       }
    }

API CALL:

    await http.post("http://calikidsmap.com/test.php").then((response){

    var ddd=jsonDecode(response.body);

    Country_object_list = (ddd as List)
      .map((data) => new country.fromJson(data))
      .toList();
3