Flutter - 映射 JSON
Posted
技术标签:
【中文标题】Flutter - 映射 JSON【英文标题】:Flutter - Map JSON 【发布时间】:2020-05-20 20:42:02 【问题描述】:我是 DART / FLUTER 的新手,仍然有很多困难。我有一个注册功能,我需要返回 Json MAP 中的 2 个属性。构造下面的函数但返回错误
[错误:flutter/lib/ui/ui_dart_state.cc(157)]未处理异常:类型_InternalLinkedHashMap'不是List类型的子类型
你能帮帮我吗?
关于我的代码:
saveClient(Cliente cliente) async
final Map<String, dynamic> clienteMap =
"nome": cliente.nome,
"email": cliente.email,
"senha": cliente.senha,
"celular": cliente.celular,
;
final String clientJson = jsonEncode(clienteMap);
client.post(baseUrl + '/usuario',
headers: 'Content-type': 'application/json', 'password': 'admin',
body: clientJson);
final Response response = await client.get(baseUrl + '/usuario/id');
final List<dynamic> decodedJson = jsonDecode(response.body);
final List<ClienteDto> dataUser = List();
for (Map<String, dynamic> clienteJson in decodedJson)
final ClienteDto cliente = ClienteDto(
clienteJson['id'],
clienteJson['nome'],
);
dataUser.add(cliente);
print(dataUser);
return dataUser;
【问题讨论】:
您在哪一行收到此错误?没有更多细节很难给出答案。 这一行:final List您正在尝试将解码后的 JSON 响应(Map
)分配给无效分配的 List
。您应该尝试打印jsonDecode(response.body)
的结果,以找出您关心的结果的实际部分在响应中的位置。
【讨论】:
对不起,正如我所说,我是 Dart 语言的新手,我在 2 周前才开始使用它。代码中的打印只是为了测试目的。我真正需要的是将作为注册数据发送的 [id] 和 [nome] 的值分配给一个变量。我怎样才能做到这一点? 没问题,我很乐意提供帮助。你能分享jsonDecode(response.body)
的输出吗?
只是提醒@Hudson_Nunes - 你没有更新你的帖子,你添加了一个更新来回答你的问题。您应该获取其他内容并将其添加到您的问题中,因为它不是您问题的有效答案。
+1 到 BJHStudios 评论。此外,您似乎没有发出有效的请求,因此您的响应正文包含错误。
感谢您的评论。我会在另一篇文章中重新提出我的问题。【参考方案2】:
这是我的 WebClient 类的所有代码:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:http_interceptor/http_interceptor.dart';
import 'package:owlwee/Models/Cartao.dart';
import 'package:owlwee/Models/Cliente.dart';
import 'package:owlwee/Models/ClienteDto.dart';
final Client client =
HttpClientWithInterceptor.build(interceptors: [LoggingInterceptor()]);
const String baseUrl = 'http://xxxxxxxxxxxxxx:8080'; // LEROMA
const String baseUrlCheckIn = 'http://xxxxxxxxxxxxx:8081'; // LEROMA
class LoggingInterceptor implements InterceptorContract
@override
Future<RequestData> interceptRequest(RequestData data) async
print('Request');
print('Headers: $data.headers');
print('body: $data.body');
return data;
@override
Future<ResponseData> interceptResponse(ResponseData data) async
print('Status $data.statusCode');
print('Headers: $data.headers');
print('body: $data.body');
return data;
saveClient(Cliente cliente) async
final Map<String, dynamic> clienteMap =
"nome": cliente.nome,
"email": cliente.email,
"senha": cliente.senha,
"celular": cliente.celular,
;
final String clientJson = jsonEncode(clienteMap);
client.post(baseUrl + '/usuario',
headers: 'Content-type': 'application/json', 'password': 'admin',
body: clientJson);
final Response response = await client.get(baseUrl + '/usuario/id');
final List<dynamic> decodedJson = jsonDecode(response.body);
final List<ClienteDto> dataUser = List();
for (Map<String, dynamic> clienteJson in decodedJson)
final ClienteDto cliente = ClienteDto(
clienteJson['id'],
clienteJson['nome'],
);
dataUser.add(cliente);
print(dataUser);
return dataUser;
这是控制台的答案:
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device android SDK built for x86...
I/flutter (15631): Request
I/flutter (15631): Headers: Content-type: application/json; charset=utf-8, password: admin
I/flutter (15631): body: "nome":"Hudson","email":"hudson@email.com","senha":"123456","celular":21987987987
I/flutter (15631): Request
I/flutter (15631): Headers:
I/flutter (15631): body:
I/flutter (15631): Status 400
I/flutter (15631): Headers: connection: close, content-type: application/json, date: Wed, 05 Feb 2020 00:38:37 GMT, transfer-encoding: chunked
I/flutter (15631): body: "timestamp":"2020-02-05T00:38:37.040+0000","status":400,"error":"Bad Request","message":"Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: \"id\"","trace":"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: \"id\"\r\n\tat org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(Invocable
E/flutter (15631): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
E/flutter (15631): #0 saveClient (package:owlwee/http/webclient.dart:83:23)
E/flutter (15631): <asynchronous suspension>
E/flutter (15631): #1 _CadastroState.build.<anonymous closure> (package:owlwee/Views/Cadastro.dart:192:25)
E/flutter (15631): #2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (15631): #3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (15631): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (15631): #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (15631): #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (15631): #7 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
E/flutter (15631): #8 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (15631): #9 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
E/flutter (15631): #10 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (15631): #11 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (15631): #12 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (15631): #13 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (15631): #14 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (15631): #15 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (15631): #16 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (15631): #17 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (15631): #18 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (15631):
I/flutter (15631): Status 201
I/flutter (15631): Headers: content-type: application/json, location: http://192.168.1.9:8080/usuario/9, date: Wed, 05 Feb 2020 00:38:37 GMT, transfer-encoding: chunked
I/flutter (15631): body: "id":9,"nome":"Hudson"
这是你问的吗?
【讨论】:
以上是关于Flutter - 映射 JSON的主要内容,如果未能解决你的问题,请参考以下文章