我如何在 Flutter/dart 中反序列化我的 json

问题描述

我对颤振很陌生,现在我陷入了将 json 字符串消毒到我的班级中的问题。 感谢您在这方面的帮助。

这是我的json

[
 {   
    "itemno": "4800888136473","itemname": "AXE DEO AFRICA 150ML",},{  
    "itemno": "4800888141125","itemname": "AXE DEO BODYSPRAY DARK TMPTTN 150ML",}
]

还有我的 JSON 类

class ListItemList{
  ListItemList({   
    this.itemno,this.itemname,});


  String itemno;
  String itemname;
  

  factory ListItemList.fromJson(Map<String,dynamic> json) =>
      ListItemList(       
        itemno: json["itemno"],itemname: json["itemname"],);
}

我怎么打电话

  List<ListItemList> result =
              ListItemList.fromJson(jsonDecode(response.body));

解决方法

使用 map 迭代列表 JSON。

final List<ListItemList> result = (jsonDecode(response.body) as List)
    .map((e) => ListItemList.fromJson(e))
    .toList();
,

正如我提到的,它是一个列表。像处理列表一样;

 List<ListItemList> result;
     var a = jsonDecode(response.body);
    
    
    // I can not compile this part you can check syntax
    a.forEach((element)
    at= ListItemList.fromJson(element);
    result.add(at);
    );
     
,

检查此链接“https://app.quicktype.io/”

在左侧粘贴您的 json 代码并添加类模型名称。

例如。

import 'dart:convert';

List<User> userFromJson(String str) => List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User {
    User({
        this.itemno,this.itemname,});

    String itemno;
    String itemname;

    factory User.fromJson(Map<String,dynamic> json) => User(
        itemno: json["itemno"] == null ? null : json["itemno"],itemname: json["itemname"] == null ? null : json["itemname"],);

    Map<String,dynamic> toJson() => {
        "itemno": itemno == null ? null : itemno,"itemname": itemname == null ? null : itemname,};
}

//在服务中添加以下代码

static Future<List<User>> getUsers() async {
 List<User> users = usersFromJson(response.body));
 return users;
}

// 在特定页面调用服务

列出_users;

@override
  void initState() {
    super.initState();
    ApiService.getUsers().then((value) {
          setState(() {
            _users = value;
          });
        })
}
,

转到此 URL 并粘贴您的 JSON。它会将其转换为 fromJson(json 到 dart 对象转换)和 toJson(dart 对象到 json 转换)函数。

根据您提供的 Json,这里是 fromJson 和 toJosn 的示例

ansible-playbook --extra-vars "http_proxy=$http_proxy" ...