簡體   English   中英

問題將 json 響應轉換為 Flutter 中的 object

[英]problem converting json response to object in Flutter

首先對我的“英語”感到抱歉...我正在嘗試使用 API 方法使用 http package13CC2686.B7D8Z 我能夠從 API 獲得響應,但我無法嘗試 map 對我的自定義 object 的響應(json)調用 APILoginResponse。

我正在調用 API 方法,如下所示:

APILoginResponse apiLogin = await api.apiLogin();

但我收到運行時錯誤“動態不是 AccessToken 的子類型”。

這是我的 API 登錄方法:

Future<APILoginResponse> apiLogin() async {
  final http.Response response = await http.post(
    api_end_point + '/api/Auth/login',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(
        <String, String>{'userName': api_user, 'password': api_password}),
  );
  if (response.statusCode == 200) {
    return APILoginResponse.fromJson(json.decode(response.body));
  } else {
    throw Exception('Error en login de la API');
  }
}

...這是我的 APILoginResponse object:

class APILoginResponse {
  final AccessToken accessToken;
  final String refreshToken;

  APILoginResponse({this.accessToken, this.refreshToken});

  factory APILoginResponse.fromJson(Map<String, dynamic> json) {
    return APILoginResponse(
      accessToken: json['accessToken'],
      refreshToken: json['refreshToken'],
    );
  }
}

class AccessToken {
  String token;
  int expiresIn;
}

錯誤在行中:

accessToken: json['accessToken']

在 APILoginResponse class 內部。

這是我的 json 回復:

{
  "accessToken": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiIiLCJzdWIiOiJib3N0b25jcmVkX2NsaWVudGVzIiwianRpIjoiZjBkMzY0ZDMtMmRkNS00NzkzLWE5ZTktMzY1YzJmODNiYmI3IiwiaWF0IjoxNTk0MTMxODAwLCJyb2wiOiJhcGlfYWNjZXNzIiwiaWQiOiIyMzg3YTMzZi1hYzE5LTRhMzYtODcyZC04MTE3MzExZDFjY2IiLCJuYmYiOjE1OTQxMzE3OTksImV4cCI6MTU5NDEzMjM5OSwiaXNzIjoid2ViQXBpIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzMTcvLyJ9.PqCPkVct4e4duWFEr63fALZ0h_0x25vsV_GBx336Apw",
    "expiresIn": 600
  },
  "refreshToken": "W6wyiw9xYuC2UaJmyCOYujKIZTs0jAscnfcWTrEyVIk="
}

對此的任何幫助將不勝感激。 謝謝!

如果你確定返回值是一個AccessToken你可以試試這個:

  factory APILoginResponse.fromJson(Map<String, dynamic> json) {
   return APILoginResponse(
   accessToken: (json['accessToken'] as Map<String,dynamic>) as AccessToken ?? null,
   refreshToken: json['refreshToken'],
   );
 }

將您的 AccessToken class 更改為:

class AccessToken {
   final Map<String,dynamic> tokenData;
   AccessToken(tokenData)
}

好吧,我認為@P4yam 的答案是正確的,但我一遍又一遍地遇到同樣的錯誤,所以我更改了我的 APILoginResponse class 如下:

class APILoginResponse {
  AccessToken accessToken;
  String refreshToken;

  APILoginResponse({this.accessToken, this.refreshToken});

  APILoginResponse.fromJson(Map<String, dynamic> json) {
    accessToken = json['accessToken'] != null
        ? new AccessToken.fromJson(json['accessToken'])
        : null;
    refreshToken = json['refreshToken'];
  }

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

class AccessToken {
  String token;
  int expiresIn;

  AccessToken({this.token, this.expiresIn});

  AccessToken.fromJson(Map<String, dynamic> json) {
    token = json['token'];
    expiresIn = json['expiresIn'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['token'] = this.token;
    data['expiresIn'] = this.expiresIn;
    return data;
  }
}

現在一切正常! 謝謝!

Flutter - 將 map 的 Json map 轉換為列表<object>在 flutter<div id="text_translate"><p> 我正在嘗試在父 class 中反序列化 json。 我的其中一個項目是 Map 的 Map,我想將其反序列化為 class 類型。 由於 map 中嵌套的 map ,我正在努力解析它,我不清楚正確的語法。 歸根結底,我想要父 class 中的列表。 json 類型塊中的項目是動態的,因此可能存在具有不同描述的關鍵、通知等類型。</p><p> <strong>Json 樣品:</strong></p><pre> { "types":{ "alert":{ "description":"Action item." }, "question":{ "description":"Select an applicable response." }, "info":{ "description":"This is an information message, no action required." } } }</pre><p> <strong>class 類型:</strong></p><pre> class Types { final String name; final String description; Types({ required this.name, required this.description, }); factory Types.fromJson(String id, Map&lt;String, dynamic&gt; json) { return Types( name: id, description: json['description'] == null? '': json['description'], ); } }</pre><p> <strong>父 class:</strong></p><pre> class Parent { final String id; final String name; final String description; final Features features; final List&lt;Types&gt; types; final List&lt;String&gt; users; Parent({ required this.id, required this.name, required this.description, required this.features, required this.types, required this.users, }); factory Parent.fromJson( Map&lt;String, dynamic&gt; json) { return Parent( id: json['id'] == null? '': json['id'], name: json['name'] == null? '': json['name'], description: json['description'] == null? '': json['description'], features: json['features'] == null? Features(): Features.fromJson(json['features']), types: json['types'] == null? []: //??? How to deserialize Map{Map{}}, users: json['users'] == null? []: List&lt;String&gt;.from(json['users']), ); } }</pre><p> 任何和所有的幫助表示贊賞。 同樣,如果有更好的方法來存儲這些數據,我對此持開放態度。 class 類型允許我在必要時添加未來的字段。</p><p> 謝謝你。</p></div></object>

[英]Flutter - Converting Json map of a map to List<Object> in flutter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 在顫振中使用 Chopper 庫將 JSON 響應轉換為模型對象? JSON響應並將其轉換為JSON對象 將 JSON 對象轉換為響應對象 將JSON響應轉換為python對象 將JSON響應轉換為Java對象 json響應中的空格未轉換為php對象 將JSON對象轉換為PHP數組時出現問題 如何在 Flutter 中將響應 JSON 轉換為對象? Flutter - 將 map 的 Json map 轉換為列表<object>在 flutter<div id="text_translate"><p> 我正在嘗試在父 class 中反序列化 json。 我的其中一個項目是 Map 的 Map,我想將其反序列化為 class 類型。 由於 map 中嵌套的 map ,我正在努力解析它,我不清楚正確的語法。 歸根結底,我想要父 class 中的列表。 json 類型塊中的項目是動態的,因此可能存在具有不同描述的關鍵、通知等類型。</p><p> <strong>Json 樣品:</strong></p><pre> { "types":{ "alert":{ "description":"Action item." }, "question":{ "description":"Select an applicable response." }, "info":{ "description":"This is an information message, no action required." } } }</pre><p> <strong>class 類型:</strong></p><pre> class Types { final String name; final String description; Types({ required this.name, required this.description, }); factory Types.fromJson(String id, Map&lt;String, dynamic&gt; json) { return Types( name: id, description: json['description'] == null? '': json['description'], ); } }</pre><p> <strong>父 class:</strong></p><pre> class Parent { final String id; final String name; final String description; final Features features; final List&lt;Types&gt; types; final List&lt;String&gt; users; Parent({ required this.id, required this.name, required this.description, required this.features, required this.types, required this.users, }); factory Parent.fromJson( Map&lt;String, dynamic&gt; json) { return Parent( id: json['id'] == null? '': json['id'], name: json['name'] == null? '': json['name'], description: json['description'] == null? '': json['description'], features: json['features'] == null? Features(): Features.fromJson(json['features']), types: json['types'] == null? []: //??? How to deserialize Map{Map{}}, users: json['users'] == null? []: List&lt;String&gt;.from(json['users']), ); } }</pre><p> 任何和所有的幫助表示贊賞。 同樣,如果有更好的方法來存儲這些數據,我對此持開放態度。 class 類型允許我在必要時添加未來的字段。</p><p> 謝謝你。</p></div></object> Flutter 從 Json 轉換嵌套對象返回 null
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM