将json repsonse转换为字符串并将其放入结构中

时间:2019-07-09 13:08:47

标签: json api mobile flutter dart

我正在制作一个用于购物的移动应用

我想用json在线数据替换静态数据,并将其放在结构中以使用 Gridview 进行显示,并在其他地方使用 这就是结构:

    class Product {

  String _urlToImage;
  String _about;
  String _title;
  double _price;
  double _weight;
  int _id;


  Product(this._urlToImage, this._title, this._price, this._weight, this._id){
    _about = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
  }

  double get weight => _weight;

  double get price => _price;

  String get title => _title;

  String get urlToImage => _urlToImage;

  int get id => _id;

  String get about => _about;


}
```

这是结构内部的本地数据

  class ProductsRepository{

List<Product>  fetchAllProducts() {

return [
  new Product("assets/images/spelt_noodles.png", "Biona Organic Spelt Noodles", 2.99, 250, 0),
  new Product("assets/images/spelt_italian.png", "Biona Organic Spelt Fusili Brown", 2.35, 500, 1),
  new Product("assets/images/spelt_spaghetti.png", "Biona Organic Whole Spelt Spaghetti", 2.35, 500, 2),
  new Product("assets/images/spelt_tagliatelle.png", "Biona Organic Spelt Spinach Artisan Tagliatelle", 1.99, 250, 3),
  new Product("assets/images/spelt_penne.png", "Biona Organic Whole Spelt Penne", 2.35, 500, 4),
  new Product("assets/images/spelt_tagliatelle.png", "Biona Organic Spelt Spinach Artisan Tagliatelle", 1.99, 250, 5),
  new Product("assets/images/spelt_fusilli.png", "Biona Organic Spelt Fusilli Tricolore", 1.99, 250, 6),
];}

我尝试了

  _fetchData() async {

    final response =
    await http.get("https://jsonplaceholder.typicode.com/photos");
        if (response.statusCode == 200) {
          list = json.decode(utf8.decode(response.bodyBytes)) as List;

    } else {
    throw Exception('Failed to load photos');
    }
  }

就像这个概念一样,但是json数据应该在Product()结构中

List data;

Future<String> getData() async {
  var response = await http.get(
      Uri.encodeFull("https://aflam4app.de/JSON/" + widget.thisJson +".json"),
      headers: {
        'Content-Type': 'application/json',
        "Accept": "application/json"
      }
  );

  this.setState(() {
    data = json.decode(utf8.decode(response.bodyBytes));
  });
  return "Success!";
}


@override
void initState() {
  super.initState();
  this.getData();
}

@override
Widget build(BuildContext context) {
  return GridView.builder(
      itemCount: data == null ? 0 : data.length,
      gridDelegate:
      new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (BuildContext context, int index) {
        return Padding(
          padding: const EdgeInsets.all(4.0),
          child: Single_prod(
            prod_name: data[index]['name'],
            prod_pricture: data[index]['picture'],
            prod_link: data[index]['link'],
            prod_description: data[index]['description'],
            prod_type: data[index]['type'],
          ),
        );
      });
}
}

class Single_prod extends StatelessWidget {
final prod_name;
final prod_pricture;
final prod_link;
final prod_description;
final prod_type;

Single_prod({
  this.prod_name,
  this.prod_pricture,
  this.prod_link,
  this.prod_description,
  this.prod_type,
});

这是我的json文件:

[
    {
        "urlToImage": "assets/images/spelt_noodles.png",
        "title": "Biona Organic Spelt Noodles",
        "price": 2.99,
        "weight": 250,
        "id": 1,
        "created_at": "2019-07-07 10:44:53",
        "updated_at": "2019-07-07 10:44:53"
    },
    {
        "urlToImage": "assets/images/spelt_noodles.png",
        "title": "Biona Organic Spelt Noodles",
        "price": 2.99,
        "weight": 250,
        "id": 2,
        "created_at": "2019-07-07 10:44:53",
        "updated_at": "2019-07-07 10:44:53"
    },
    {
        "urlToImage": "assets/images/spelt_noodles.png",
        "title": "Biona Organic Spelt Noodles",
        "price": 2.99,
        "weight": 250,
        "id": 3,
        "created_at": "2019-07-07 10:44:53",
        "updated_at": "2019-07-07 10:44:53"
    },


]

2 个答案:

答案 0 :(得分:2)

这是解析数据的方式

    List<Product> list = new List<Product>();
    var map= json.decode(response.body);

    for(var item in map){
      Product product = new Product.fromJson(item); //making an assumption how your json looks
      list.add(product); //user a Futurebuilder to create your GridView
    }

这是定义模型类的方式

    Product fromJson(Map<String, dynamic> json){
      Product product = new Product(
        _urlToImage = json['urlToImage'] as String;
        _about = json['about'] as String;
        _title = json['title'] as String;
        _price = json['price'] as double;
        _weight = json['weight'] as double;
        _id = json['id'] as int;
      );
      return product;
    }

    ...

Here Gridview示例

答案 1 :(得分:0)

另一种方式。

import 'dart:convert';

import 'json_objects.dart';

void main() {
  var json = (jsonDecode(body) as List).cast<Map<String, dynamic>>();
  var list = json.map<Response1>((e) => Response1.fromJson(e)).toList();
  for (var item in list) {
    print(item.id);
    print(item.title);
  }
}

final body = '''
[
  {
    "urlToImage": "assets/images/spelt_noodles.png",
    "title": "Biona Organic Spelt Noodles",
    "price": 2.99,
    "weight": 250,
    "id": 1,
    "created_at": "2019-07-07 10:44:53",
    "updated_at": "2019-07-07 10:44:53"
  },
  {
    "urlToImage": "assets/images/spelt_noodles.png",
    "title": "Biona Organic Spelt Noodles",
    "price": 2.99,
    "weight": 250,
    "id": 2,
    "created_at": "2019-07-07 10:44:53",
    "updated_at": "2019-07-07 10:44:53"
  },
  {
    "urlToImage": "assets/images/spelt_noodles.png",
    "title": "Biona Organic Spelt Noodles",
    "price": 2.99,
    "weight": 250,
    "id": 3,
    "created_at": "2019-07-07 10:44:53",
    "updated_at": "2019-07-07 10:44:53"
  }
]''';

结果:

1
Biona Organic Spelt Noodles
2
Biona Organic Spelt Noodles
3
Biona Organic Spelt Noodles

JSON数据模型(安全,具有正确的数据转换)。

class Response1 {
  final String createdAt;
  final int id;
  final double price;
  final String title;
  final String updatedAt;
  final String urlToImage;
  final int weight;

  Response1(
      {this.createdAt,
      this.id,
      this.price,
      this.title,
      this.updatedAt,
      this.urlToImage,
      this.weight});

  factory Response1.fromJson(Map<String, dynamic> json) {
    return Response1(
      createdAt: json['created_at'] as String,
      id: json['id'] as int,
      price: _toDouble(json['price']),
      title: json['title'] as String,
      updatedAt: json['updated_at'] as String,
      urlToImage: json['urlToImage'] as String,
      weight: json['weight'] as int,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'created_at': createdAt,
      'id': id,
      'price': price,
      'title': title,
      'updated_at': updatedAt,
      'urlToImage': urlToImage,
      'weight': weight,
    };
  }
}

double _toDouble(data) {
  if (data == null) {
    return null;
  }
  if (data is int) {
    return data.toDouble();
  }
  return data as double;
}

/*
Response1:
  "urlToImage": String
  "title": String
  "price": double
  "weight": int
  "id": int
  "created_at": String
  "updated_at": String
*/