将json数据从本地列表更改为在线文件

时间:2019-07-10 23:12:40

标签: android mysql json api flutter

我将此数据列表作为 String ,我想将其存储在JSON文件中,然后再次将其称为 String ,以将其保留在列表, 但由于数据类型而引发错误

这是代码

I tried below code as well.
var id = $('#id').val();
                $.ajax({
                    url:'registration_detail.php',
                    method:'POST',
                    data: { id: id},
                   success: function(response) {
            $('#result').html(response);
        }
                });

我尝试了

import 'package:project/models/Response.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
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_spaghetti.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"
  }
]''';

class ProductsRepository{


    List<Product>  fetchAllProducts() {

    var jsonB = (jsonDecode(body) as List).cast<Map<String, dynamic>>();
    var list = jsonB.map<Response1>((e) => Response1.fromJson(e)).toList();

     List<Product> items = [];

      for (var item in list) {
        items.add(new Product(item.urlToImage, item.title, item.price, item.price, item.id));
      }

    return items;

  }

但是会引发错误, 那么如何通过http获取json文件并将其转换为字符串以将其提供给jsonDecode( body )?

1 个答案:

答案 0 :(得分:0)

response.body已经是一个字符串,您无需执行任何操作。

Future<String> getData() async {
  response = await http.get('https://example.json');
  return response.body;
}