【问题标题】:Flutter: How to convert String to Map<String, dynamic> in jsonFlutter:如何在 json 中将 String 转换为 Map<String, dynamic>
【发布时间】:2020-08-22 21:44:32
【问题描述】:

我正在使用 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}

【问题讨论】:

  • 你能添加你得到的responce.body吗?我的意思是你的 json 是什么。
  • 发布您的 JSON 的外观@Nithin Sai
  • 是的,请发布jsonDecode(response) 的样子
  • @VirenVVarasadiya 看看??
  • @JagrajSingh 检查?

标签: json api flutter


【解决方案1】:

我正在使用 Dio 包。

1,将响应体解析为模型。

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

2、有了Model,让我们使用代码生成(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,
    };

【讨论】:

    猜你喜欢
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2020-01-10
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多