【问题标题】:Writing and Reading JSON files locally in Flutter Doesn't include Quotes在 Flutter 中本地写入和读取 JSON 文件不包含引号
【发布时间】:2020-11-08 14:35:54
【问题描述】:

我正在将一个对象写入本地的 JSON 文件。当我尝试阅读它时,我收到此错误:

E/flutter ( 7621): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter ( 7621): {players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}
E/flutter ( 7621):  ^

我了解我收到此错误的原因是因为 player 不在引号之间。即“玩家”。我不知道如何将对象写为包含引号的 JSON。

此代码由 JsonSerializableGenerator 生成
PlayerList.toJson:

PlayerList _$PlayerListFromJson(Map<String, dynamic> json) {
  return PlayerList(
    (json['players'] as List)
        ?.map((e) =>
            e == null ? null : Player.fromJson(e as Map<String, dynamic>))
        ?.toList(),
  );
}

Map<String, dynamic> _$PlayerListToJson(PlayerList instance) =>
    <String, dynamic>{
      'players': instance.players?.map((e) => e?.toJson())?.toList(),
    };

这是我读写文件的方式:

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/playerData.json');
}

Future<File> writePlayerData(PlayerList playerList) async {
  final file = await _localFile;
  return file.writeAsString(playerList.toJson().toString());
}

Future<PlayerList> readPlayerData () async {
  try {
    final file = await _localFile;
    String contents = await file.readAsString();
    final jsonResponse = jsonDecode(contents);
    PlayerList playerList = PlayerList.fromJson(jsonResponse);
    return playerList;
  } catch (e) {
    print(e);
    return getPlayerList(); //just loads a placeholder json in the assets folder;
  }
}

我希望将 JSON 格式化为:

{
  "players": [
    {
      "id": "Filler Character",
      "setCount": "0 - 0",
      "characters": {
        "char1": "",
        "char2": ""
      },
      "notes": "Filler Character"
    }
  ]
}

程序保存的内容:

{players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}

我需要手动将引号重新添加到 JSON 中,还是有其他保存方式?

【问题讨论】:

  • 字符串内容 = await file.readAsString();最终 jsonResponse = jsonEncode(jsonDecode(contents));
  • 只编码你的json
  • 我补充说。 jsonEncode(jsonDecode(内容));现在我得到一个错误: PlayerList playerlist = PlayerList.fromJson(jsonResponse);错误是:参数类型“String”不能分配给参数类型“Map”。
  • jsonDecode(jsonEncode(contents)); ...哦,只是替换

标签: json flutter dart


【解决方案1】:

如果您在 2021 年遇到上传文件问题。在 REST API 或本地服务器上上传文件的最佳方式

     Future<ApiResponse<bool>> uploadfile(File file) async {

    var stream = new http.ByteStream(DelegatingStream(file.openRead()));
    var length = await file.length();
    var uri = Uri.parse("Enter your URL");
    var request = new http.MultipartRequest("POST", uri);
    var multipartFile = new http.MultipartFile('data', stream, length, filename: basename(file.path));
    request.files.add(multipartFile);
    await request.send().then((response) {
      response.stream.transform(utf8.decoder).listen((value) {
      file.delete();
        print(value);
      });

    }).catchError((e) {
      print(e);
    });
  }

制作本地 JSON 文件的代码

     void makeJsonFile(Map<String, List> value) async 
 {
     final Directory directory = await getApplicationDocumentsDirectory();
     final File file = File('${directory.path}/360feedback.json');
  
     await file.writeAsString(jsonEncode(value));

      RecordService>.uploadfile(file).then((value) {
           
                  });
  }

【讨论】:

    【解决方案2】:

    尝试以下方法,对我来说效果很好:

      Map<String,dynamic> a = {'a' : 'b', 'c' : {'d' : 'e'}};
      void _go () async  {
        final Directory directory = await getApplicationDocumentsDirectory();
        final File file = File('${directory.path}/a.json');
        await file.writeAsString(json.encode(a));
        Map<String, dynamic> myJson = await json.decode(await file.readAsString());
        print(myJson.toString());
      }
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 2020-05-13
      • 2020-08-21
      • 1970-01-01
      相关资源
      最近更新 更多