flutter 未处理的异常:格式异常:意外字符(位于字符2处){_id:6414 a040 c 01 cb 2fbea 9 ede 6c,我正在尝试从mongodb检索数据

mwngjboj  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(128)

聊天室服务

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:onpods/constants/http_error_handelling.dart';
import 'package:onpods/constants/utils.dart';
import 'package:onpods/models/chat_room_model.dart';
import 'package:onpods/models/user_model.dart';
import 'package:http/http.dart' as http;
import 'package:onpods/providers/user_provider.dart';
import 'package:onpods/view/chat_room.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';

import '../../constants/global_constants.dart';

class ChatRoomServices {
  void getChatRoomIndex({
    required BuildContext context,
  }) async {
    http.Response res = await http.get(
      Uri.parse("$uri/get-all-room-index"),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );

    print("skjnv");
    print(jsonDecode(res.body)[0]);

    List<ChatRoomModel> allChatRooms = [];

    for (var e in jsonDecode(res.body)) {
      ChatRoomModel temp = ChatRoomModel.fromJson(e.toString());
      allChatRooms.add(temp);
      print(temp.chatTopic);
      print(temp.chatTopic);
    }

    print("skjnv");

    ChatRoom chatRoom;
    // ignore: use_build_context_synchronously
    httpErrorHandle(
      response: res,
      context: context,
      onSuccess: () async {},
    );
  }
}

聊天室模型

import 'dart:convert';

// ignore_for_file: public_member_api_docs, sort_constructors_first
class ChatRoomModel {
  String chatTopic;
  String roomType;
  Map<String, dynamic> ownerId;
  List<Map<String, dynamic>> speakers;
  List<Map<String, dynamic>> participants;
  String createdAt;
  String updatedAt;
  ChatRoomModel({
    required this.chatTopic,
    required this.roomType,
    required this.ownerId,
    required this.speakers,
    required this.participants,
    required this.createdAt,
    required this.updatedAt,
  });

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'chatTopic': chatTopic,
      'roomType': roomType,
      'ownerId': ownerId,
      'speakers': speakers,
      'participants': participants,
      'createdAt': createdAt,
      'updatedAt': updatedAt,
    };
  }

  factory ChatRoomModel.fromMap(Map<String, dynamic> map) {
    return ChatRoomModel(
      chatTopic: map['chatTopic'] as String,
      roomType: map['roomType'] as String,
      ownerId: Map<String, dynamic>.from((map['ownerId'] as Map<String, dynamic>)),
      speakers: List<Map<String, dynamic>>.from(
        (map['speakers'] as List<int>).map<Map<String, dynamic>>(
          (x) => x as Map<String, dynamic>,
        ),
      ),
      participants: List<Map<String, dynamic>>.from(
        (map['participants'] as List<int>).map<Map<String, dynamic>>(
          (x) => x as Map<String, dynamic>,
        ),
      ),
      createdAt: map['createdAt'] as String,
      updatedAt: map['updatedAt'] as String,
    );
  }

  String toJson() => json.encode(toMap());

  factory ChatRoomModel.fromJson(String source) {
    print("Sajs");
    print(source);
    return ChatRoomModel.fromMap(json.decode(source) as Map<String, dynamic>);
  }
}

Postman请求响应(/get-all-room-index)

[
    {
        "_id": "6414a040c01cb2fbea9ede6c",
        "chatTopic": "Current Affairs",
        "roomType": "public",
        "ownerId": {
            "isPublic": true,
            "_id": "6405fe3df459de43b5dadb78",
            "user_name": "Simran Bhalode",
            "user_email": "simran@gmail.com",
            "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
            "user_role": "admin",
            "registered_date": "2023-03-06T14:52:45.847Z",
            "__v": 0
        },
        "speakers": [
            {
                "isPublic": true,
                "_id": "6405fe3df459de43b5dadb78",
                "user_name": "Simran Bhalode",
                "user_email": "simran@gmail.com",
                "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
                "user_role": "admin",
                "registered_date": "2023-03-06T14:52:45.847Z",
                "__v": 0
            }
        ],
        "participants": [],
        "createdAt": "2023-03-17T17:15:44.873Z",
        "updatedAt": "2023-03-17T17:15:44.873Z",
        "__v": 0
    },
    {
        "_id": "6415e11ddd95481799b016f7",
        "chatTopic": "Current Affairs",
        "roomType": "public",
        "ownerId": {
            "isPublic": true,
            "_id": "6405fe3df459de43b5dadb78",
            "user_name": "Simran Bhalode",
            "user_email": "simran@gmail.com",
            "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
            "user_role": "admin",
            "registered_date": "2023-03-06T14:52:45.847Z",
            "__v": 0
        },
        "speakers": [
            {
                "isPublic": true,
                "_id": "6405fe3df459de43b5dadb78",
                "user_name": "Simran Bhalode",
                "user_email": "simran@gmail.com",
                "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
                "user_role": "admin",
                "registered_date": "2023-03-06T14:52:45.847Z",
                "__v": 0
            }
        ],
        "participants": [],
        "createdAt": "2023-03-18T16:04:45.928Z",
        "updatedAt": "2023-03-18T16:04:45.928Z",
        "__v": 0
    }
]

错误为

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Unexpected character (at character 2)
{_id: 6414a040c01cb2fbea9ede6c, chatTopic: Current Affairs, roomType: publi...
 ^
#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
#1      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:913:48)
#2      _parseJson (dart:convert-patch/convert_patch.dart:35:10)
#3      JsonDecoder.convert (dart:convert/json.dart:610:36)
#4      JsonCodec.decode (dart:convert/json.dart:216:41)
#5      new ChatRoomModel.fromJson
chat_room_model.dart:59
#6      ChatRoomServices.getChatRoomIndex
chat_room_services.dart:33
<asynchronous suspension>
*

Postman 成绩
我试着改变转换去数据类型,但没有工作,任何人都可以请建议我一个更好的解决方案,这是显示错误的_id,但为什么我不知道。

[
    {
        "_id": "6414a040c01cb2fbea9ede6c",
        "chatTopic": "Current Affairs",
        "roomType": "public",
        "ownerId": {
            "isPublic": true,
            "_id": "6405fe3df459de43b5dadb78",
            "user_name": "Simran Bhalode",
            "user_email": "simran@gmail.com",
            "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
            "user_role": "admin",
            "registered_date": "2023-03-06T14:52:45.847Z",
            "__v": 0
        },
        "speakers": [
            {
                "isPublic": true,
                "_id": "6405fe3df459de43b5dadb78",
                "user_name": "Simran Bhalode",
                "user_email": "simran@gmail.com",
                "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
                "user_role": "admin",
                "registered_date": "2023-03-06T14:52:45.847Z",
                "__v": 0
            }
        ],
        "participants": [],
        "createdAt": "2023-03-17T17:15:44.873Z",
        "updatedAt": "2023-03-17T17:15:44.873Z",
        "__v": 0
    },
    {
        "_id": "6415e11ddd95481799b016f7",
        "chatTopic": "Current Affairs",
        "roomType": "public",
        "ownerId": {
            "isPublic": true,
            "_id": "6405fe3df459de43b5dadb78",
            "user_name": "Simran Bhalode",
            "user_email": "simran@gmail.com",
            "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
            "user_role": "admin",
            "registered_date": "2023-03-06T14:52:45.847Z",
            "__v": 0
        },
        "speakers": [
            {
                "isPublic": true,
                "_id": "6405fe3df459de43b5dadb78",
                "user_name": "Simran Bhalode",
                "user_email": "simran@gmail.com",
                "user_password": "$2b$07$VPHjLNYKicBcEgfyRNT9i.8zok9kU7XqNlNgnpAsZ5V9FN/oyKUka",
                "user_role": "admin",
                "registered_date": "2023-03-06T14:52:45.847Z",
                "__v": 0
            }
        ],
        "participants": [],
        "createdAt": "2023-03-18T16:04:45.928Z",
        "updatedAt": "2023-03-18T16:04:45.928Z",
        "__v": 0
    }
]
oprakyz7

oprakyz71#

这是你的json到dart文件id部分的格式错误,像这样使用

class Autogenerated {
  String sId;
  String chatTopic;
  String roomType;
  OwnerId ownerId;
  List<Speakers> speakers;
  List<Null> participants;
  String createdAt;
  String updatedAt;
  int iV;

  Autogenerated(
      {this.sId,
      this.chatTopic,
      this.roomType,
      this.ownerId,
      this.speakers,
      this.participants,
      this.createdAt,
      this.updatedAt,
      this.iV});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    sId = json['_id'];
    chatTopic = json['chatTopic'];
    roomType = json['roomType'];
    ownerId =
        json['ownerId'] != null ? new OwnerId.fromJson(json['ownerId']) : null;
    if (json['speakers'] != null) {
      speakers = new List<Speakers>();
      json['speakers'].forEach((v) {
        speakers.add(new Speakers.fromJson(v));
      });
    }
    if (json['participants'] != null) {
      participants = new List<Null>();
      json['participants'].forEach((v) {
        participants.add(new Null.fromJson(v));
      });
    }
    createdAt = json['createdAt'];
    updatedAt = json['updatedAt'];
    iV = json['__v'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['_id'] = this.sId;
    data['chatTopic'] = this.chatTopic;
    data['roomType'] = this.roomType;
    if (this.ownerId != null) {
      data['ownerId'] = this.ownerId.toJson();
    }
    if (this.speakers != null) {
      data['speakers'] = this.speakers.map((v) => v.toJson()).toList();
    }
    if (this.participants != null) {
      data['participants'] = this.participants.map((v) => v.toJson()).toList();
    }
    data['createdAt'] = this.createdAt;
    data['updatedAt'] = this.updatedAt;
    data['__v'] = this.iV;
    return data;
  }
}

class OwnerId {
  bool isPublic;
  String sId;
  String userName;
  String userEmail;
  String userPassword;
  String userRole;
  String registeredDate;
  int iV;

  OwnerId(
      {this.isPublic,
      this.sId,
      this.userName,
      this.userEmail,
      this.userPassword,
      this.userRole,
      this.registeredDate,
      this.iV});

  OwnerId.fromJson(Map<String, dynamic> json) {
    isPublic = json['isPublic'];
    sId = json['_id'];
    userName = json['user_name'];
    userEmail = json['user_email'];
    userPassword = json['user_password'];
    userRole = json['user_role'];
    registeredDate = json['registered_date'];
    iV = json['__v'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['isPublic'] = this.isPublic;
    data['_id'] = this.sId;
    data['user_name'] = this.userName;
    data['user_email'] = this.userEmail;
    data['user_password'] = this.userPassword;
    data['user_role'] = this.userRole;
    data['registered_date'] = this.registeredDate;
    data['__v'] = this.iV;
    return data;
  }
}

相关问题