将json响应转换为字符串并放入结构中
Posted
技术标签:
【中文标题】将json响应转换为字符串并放入结构中【英文标题】:Convert json repsonse to strings and put it in a structure 【发布时间】:2019-11-19 01:20:57 【问题描述】:我正在制作一个用于购物的移动应用程序
我想用来自 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"
,
]
【问题讨论】:
那么这里的问题是什么,您想知道如何实现gridview或将您的json转换为产品对象吗? 【参考方案1】:这是解析数据的方式
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;
...
HereGridview 示例
【讨论】:
什么不起作用?错误是什么?正如我在没有看到 Json 的情况下在回答中提到的那样,我不得不猜测。您的问题和回答非常模糊。 这一切都是为了让这些 Product(...) 数据来自我的 json 而不是已经存在的数据,所以每次我从 API 添加新产品时,它都会显示在应用程序中跨度> 您能否将您的 json 的 sn-p 添加到您的原始帖子中,以便我们查看它的结构。此外,如果您可以粘贴错误消息或使用 imgur 截屏,请将其发布在回复中,这也会很有用。 我希望你现在能理解我了 谢谢。当您测试代码时,您是否更改了我的地图代码以匹配您的 json 属性?因为它区分大小写。我最初是从 caps 开始的,但现在我已经对其进行了编辑以匹配您的 json,因此您现在创建产品应该没有问题。使用调试器断点查看它是如何工作的。以上是关于将json响应转换为字符串并放入结构中的主要内容,如果未能解决你的问题,请参考以下文章
将 UNIX 时间从 json 导入(swift 结构)转换为日期作为字符串并填充表