Flutter将带有数组子对象和对象的json转换为类映射

时间:2020-10-17 07:43:58

标签: flutter dart

在我的应用程序中,我从服务器进入categories的服务器,该服务器具有一个名为products的数组:

{
  "categories": [
    {
      "id": 1,
      "store_id": 1,
      "category_id": null,
      "page_id": null,
      "title": "cat_name",
      "image_uri": "/uploads/store/category_images/2020/1600839088.jpg",
      "created_at": "2020-09-23T02:01:28.000000Z",
      "updated_at": "2020-09-23T02:01:57.000000Z",
      "products": [
        {
          "id": 1,
          "store_categories_id": 1,
          "store_id": 1,
          "title": "title",
          "description": "111111",
          //...
        }
      ]
    }
  ],
  "slides": {
    "id": 1,
    "slide_1": "/uploads/store/store_sliders/2020/16025126045410.jpg",
    //...
  }
}

我使用上述结构创建了此类:

StoreCategories类:

@JsonSerializable()
class StoreCategories {
  final List<StoreCategoriesList> categories;

  @JsonKey(nullable: true)
  final Slides slides;

  StoreCategories(this.categories,this.slides);

  factory StoreCategories.fromJson(Map<String, dynamic> json) => _$StoreCategoriesFromJson(json);

  Map<String, dynamic> toJson() => _$StoreCategoriesToJson(this);
}

StoreCategoriesList类:

@JsonSerializable()
class StoreCategoriesList{
  final int id;

  @JsonKey(name: 'store_id')
  final int storeId;

  final String title;

  @JsonKey(name: 'image_uri')
  final String imageUri;

  @JsonKey(nullable: true)
  final List<ProductsList> products;

  StoreCategoriesList(this.id, this.storeId, this.title, this.imageUri, this.products);

  factory StoreCategoriesList.fromJson(Map<String, dynamic> json) => _$StoreCategoriesListFromJson(json);

  Map<String, dynamic> toJson() => _$StoreCategoriesListToJson(this);
}

ProductsList类:

@JsonSerializable()
class ProductsList {
  final int id;

  @JsonKey(name: 'store_categories_id')
  final int storeCategoriesId;

  @JsonKey(name: 'store_id')
  final int storeId;

  final String title;
  final String description;
  final String image;
  final int cost;

  ProductsList(this.id, this.storeCategoriesId, this.storeId, this.title, this.description, this.image, this.cost);

  factory ProductsList.fromJson(Map<String, dynamic> json) => _$ProductsListFromJson(json);

  Map<String, dynamic> toJson() => _$ProductsListToJson(this);
}

现在!如何将json结构转换为类映射?

此代码不正确:

StoreCategories.fromJson(_res.response.data.map((data) => StoreCategories.fromJson(data)));

//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.fromJson(data)));

//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.from(data)));

1 个答案:

答案 0 :(得分:1)

像您的_res.response.data这样的声音已经是“地图”或“列表”权限了?

因此只需StoreCategories.fromJson(_res.response.data)。完成!

Flutter json_serializable非常聪明,足以解码嵌套类!:)

P.S。如果您有JSON String ,请执行jsonDecode(your_json_string)以获取地图或列表。