🚚

Dart で json をオブジェクトに変換するときに int を enum に変換する

2020/11/10に公開

TL;DR

Dart で json をオブジェクトに変換するときに int を enum に変換する

C# で似たようなことをよくやっていたので
Dart(Flutter) でもやりたかった

こんなjsonを

{
  "playlist":[
    {
      "category": 0,
      "title": "Foo Video",
    },
    {
      "category": 0,
      "title": "Bar Video",
    },
    {
      "category": 1,
      "title": "Baz Music",
    }
  ]
}

こういうenumとオブジェクトに変換したいとすると

enum ContentCategory {
  video,
  music,
}

class Content {
  final ContentCategory category;
  final String title;
}

こうしてやればいい

Future<List<Content>> fetchContents() async {
  final response = await http.get('https://hoge.com/json');

  if (response.statusCode == 200) {
    final jsonMap = jsonDecode(response.body) as Map<String, dynamic>;

    final result = <Content>[];
    if (jsonMap['playlist'] != null) {
      jsonMap['playlist'].forEach((dynamic v) {
        result.add(new Content.fromJson(v as Map<String, dynamic>));
      });
    }
  
    return result;
  } else {
    throw Exception('Faild to load album.');
  }
}

enum ContentCategory {
  video,
  music,
}

class Content {
  Content(
      {this.category,
      this.title});

  factory Content.fromJson(Map<String, dynamic> json) {
    return Content(
      category: ContentCategory.values[json['category'] as int], /* これ */
      title: json['title'] as String,
    );
  }

  final ContentCategory category;
  final String title;
}

Discussion