Flutter:如何在JSON中将String转换为Map <String,dynamic>

时间:2020-05-07 14:33:08

标签: json api flutter

我正在使用api作为后端来登录时获取用户数据。

这是获取数据的代码:

  Future<dynamic> getLoginData(String _phone, bool isPhone) async {
    String endPoint = isPhone
        ? '/UserLogin_Mobile?PhoneNo=$_phone'
        : '/UserLogin?Email=$_phone';
    var response = await client
        .get('$ENDPOINT' + endPoint, headers: headers)
        .catchError((onError) {
      print(onError.toString());
    });
    print("response=>" + response.body);
    if (json.decode(response.body).toString().contains("registered"))
      print("\n\nReg");
    if (response.statusCode == 200) {
      if (json.decode(response.body).toString().contains("not found"))
        print("\n\nNot found");
      return User.fromJson(jsonDecode(response.); //TODO getting error here
    }
    return null;
  }

这是用户模型


class User {
  double id;
  String userPhone;
  String userPass;
  String userNicename;
  String userEmail;
  String userUrl;
  String userRegistered;
  String userActivationKey;
  int userStatus;
  String displayName;
  String errorDis;
  bool isSuccessfull = true;
  String statuscode;
  String message;
  String latitude;
  String longitude;
  User(
      {this.id,
      this.userPhone,
      this.userPass,
      this.displayName,
      this.userActivationKey,
      this.userEmail,
      this.userNicename,
      this.userRegistered,
      this.userStatus,
      this.statuscode,
      this.message,
      this.userUrl});

  User.initial()
      : id = 0,
        userPhone = '',
        userPass = '',
        userNicename = '',
        userEmail = '',
        userUrl = '',
        statuscode = '',
        userRegistered = '',
        userActivationKey = '',
        userStatus = 0,
        displayName = '';

  User.fromJson(Map<String, dynamic> json)
      : id = json['ID'],
        userPhone = json['user_login'],
        userPass = json['user_pass'],
        userNicename = json['user_nicename'],
        userEmail = json['user_email'],
        userUrl = json['user_url'],
        userRegistered = json['user_registered'],
        userActivationKey = json['user_activation_key'],
        userStatus = json['user_status'],
        displayName = json['display_name'],
        statuscode = json['statuscode'],
        message = json['message'],
        latitude = json['latitude'],
        longitude = json['longitude'];

  User.errorFromServer(Map<String, dynamic> json) {
    statuscode = json['statuscode'];
    message = json['message'];
  }
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['user_login'] = this.userPhone;
    data['user_pass'] = this.userPass;
    data['user_nicename'] = this.userNicename;
    data['user_email'] = this.userEmail;
    data['user_url'] = this.userEmail;
    data['user_registered'] = this.userRegistered;
    data['user_activation_key'] = this.userActivationKey;
    data['user_status'] = this.userStatus;
    data['display_name'] = this.displayName;
    data['latitude'] = this.latitude;
    data['longitude'] = this.longitude;
    return data;
  }
}

这是在TODO中显示的错误

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'

我收到此错误的原因是,在TODO,我试图将response.body(它是一个字符串)映射到Map(即用户数据)。

如何解决?还是我的问题错了吗?

编辑 这是

response.body=> {"ID":633.0,"user_login":"xxxxxxxxxx","user_pass":"xxxxxx","user_nicename":"","user_email":"","user_url":"","user_registered":"0001-01-01T00:00:00","user_activation_key":"","user_status":0,"display_name":"","latitude":null,"longitude":null}

1 个答案:

答案 0 :(得分:0)

我正在使用Dio软件包。

1,将响应主体解析为Model。

  • 检查 response.statusCode 并确定您需要解析的模型。
  • 使用 YourModel.fromJson(response.data)进行解析,不需要 jsonDecode

2,通过模型,使用代码生成(Json Model

示例:

import 'package:json_annotation/json_annotation.dart';
part 'sign_in_response.g.dart';

@JsonSerializable(
    anyMap: true
)
class SignInResponse {

  String accessToken;

  String refreshToken;

  SignInResponse(this.accessToken, this.refreshToken);

  factory SignInResponse.fromJson(Map<String, dynamic> json) => _$SignInResponseFromJson(json);

  Map<String, dynamic> toJson() => _$SignInResponseToJson(this);
}

代码生成:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'sign_in_response.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

SignInResponse _$SignInResponseFromJson(Map json) {
  return SignInResponse(
    json['accessToken'] as String,
    json['refreshToken'] as String,
  );
}

Map<String, dynamic> _$SignInResponseToJson(SignInResponse instance) =>
    <String, dynamic>{
      'accessToken': instance.accessToken,
      'refreshToken': instance.refreshToken,
    };