在Dart中将逗号分隔的字符串转换/反序列化为对象

时间:2019-06-16 20:15:55

标签: json api serialization dart deserialization

我正在尝试找到一种方法,将自定义逗号分隔的字符串反序列化为Dart中的对象。

未公开的API的响应类似于以下内容:

["Godzilla II: Król potworów","Godzilla: King of the Monsters",0,0,"Akcja,Sci-Fi",2019,132,0,"https://www.filmweb.pl/film/Godzilla+II%3A+Kr%C3%B3l+potwor%C3%B3w-2019-720753/discussion",0,1,"/07/53/720753/7873671.2.jpg",["https://1.fwcdn.pl/wv/98/94/49894/thumbnail.49894.1.jpg","https://mm.filmweb.pl/720753/godzilla_ii_krol_potworow___oficjalny_zwiastun__3_pl.iphone.mp4"],"2019-05-29","2019-06-14",0,0,0,"USA","Po pojawieniu się nowego zagrożenia Król Potworów powraca, by ponownie przywrócić w przyrodzie równowagę."]  t:43200

如您所见,基本对象结构位于[]内部,并且出现一个嵌套对象。此字符串中没有键,因此无法进行基本的json反序列化。目前可以将所有值都视为字符串,但整数和双精度数不能放在引号内。

目前,我的方法如下:

Map<String, dynamic> extractResult(String response) {
    if (response.startsWith('err')) {
      throw new Error();
    }
    final map = Map<String, dynamic>();
    final film = Film();
    final lastTColon = response.lastIndexOf('t:');
    final content = response
        .substring(0, lastTColon > 0 ? lastTColon : null)
        .replaceAll('[', '')
        .replaceAll(']', '')
        .split(',');
    for (var i = 0; i < content.length; i++) {
      map[film.keys[i]] = content[i];
    }

    return map; //this I would like to convert to Film()
}

我准备了可以将该字符串转换为的简单类。

class Film {
  List<String> keys = [
    'title',
    'originalTitle',
    'rating',
    'ratingCount',
    'category',
    'year',
    'duration',
    'year',
    'something',
    'discussionUrl',
    'something2',
    'something3',
    'poster',
    'trailerInfo',
    'worldPremiere',
    'polishPremiere',
    'something4',
    'something5',
    'something6',
    'country',
    'description'
  ];
  String title;
  String originalTitle;
  double rating;
  int ratingCount;
  String category;
  int year;
  int duration;
  int something;
  String discussionUrl;
  int something2;
  int something3;
  String poster;
  TrailerInfo trailerInfo;
  String worldPremiere;
  String polishPremiere;
  int something4;
  int something5;
  int something6;
  String country;
  String description;
}

class TrailerInfo {
  String posterUrl;
  String movieUrl;
}

不幸的是,拆分结果导致数组仍然不适合映射:

Splitted content

当前,for循环提供以下映射:

Resulting map

1 个答案:

答案 0 :(得分:1)

您可以尝试将其读取为纯json数组对象。