やりたいこと
ローカルファイルに対して json 読み書きをする。 具体的には以下。
起こった問題
ローカルファイルに json を書き込もうとすると、ダブルクォテーションが消えてしまう。
なので、読み込み時に jsonDecode
をしようとすると json の文法エラーが起きる。
問題が起こったコード
ローカルとやりとりするリポジトリクラスで、以下のように読み書きをしていた。
static Future<void> makeSampleTextFile(SampleModel sampleModel) async { const textName = 'sample.json'; final textDirectory = await _textDirectory; final file = File('$textDirectory/$textName'); await file.create(recursive: true); await file.writeAsString(sampleModel.toJson()); logger.i('Create text file path is : ', file.path); } static Future<SampleModel> getSampleModel() async { const textName = 'sample.json'; final textDirectory = await _textDirectory; final file = File('$textDirectory/$textName'); try { final content = await file.readAsString(); final json = jsonDecode(content); return SampleModel.fromJson(json); } catch (e) { logger.e(e); throw Exception('テキストファイルの中身の形式が間違っています。'); } }
すると、書き込み時に、Freezed で作成したtoJson
をしているはずなのに、ダブルクォテーションが消えた。
解決策
なんてことはない。以下のように jsonEncode
をかますだけだった。
await file.writeAsString(jsonEncode(sampleModel.toJson()));