Dominik Roszkowski
Dominik Roszkowski

Reputation: 2543

Converting/deserializing comma separated string to object in Dart

I'm trying to find a way to deserialize custom comma separated string to object in Dart.

The response from undocumented API is similar to following:

["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

As you can see the basic object structure is inside [ and ] and a single nested object appears. There are no keys in this string so basic json deserialization is not possible. All values can be considered strings at the moment, but integers and doubles are not within quotation marks.

Currently, my approach is as follows:

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()
}

I prepared simple class that this string can be converted to.

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;
}

Unfortunately, the splitting results with an array that is still not suitable to be mapped:

Splitted content

Currently, the for loop gives following map:

Resulting map

Upvotes: 0

Views: 1415

Answers (1)

Antoniossss
Antoniossss

Reputation: 32507

You can try to read it as plain json array object.

Upvotes: 1

Related Questions