You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中解析含嵌套对象的JSON时Varient类打印失败问题求助

问题分析与解决方案

看起来你遇到的问题主要来自两个核心点:JSON解析的层级错误和Varient类结构与JSON数据不匹配,两者共同导致解析失败进入catch块,打印出"Failed, no response"。


1. 核心问题拆解

(1)JSON遍历层级错误

你的返回JSON根结构是一个包含varients数组的对象:

{ "varients": [ {...}, {...}, ... ] }

但在请求代码里,你直接遍历了jsonResponse(也就是整个根Map):

for (Map<String, dynamic> i in jsonResponse) { ... }

这显然不对,因为jsonResponse是一个Map,不是数组,你需要遍历的是jsonResponse["varients"]这个数组内容。

(2)Varient类结构完全不匹配JSON数据

你定义的Varient类只有一个varients字符串字段,但JSON里的每个变体对象包含ProductId、Colour、Sizes等多个属性,直接用json["varients"]赋值会导致类型不匹配(数组无法赋值给字符串),这也是解析失败的关键原因。


2. 修正后的代码示例

第一步:重新定义匹配JSON结构的Varient类

import 'dart:convert';

// 解析JSON根对象的工具类
VarientRoot varientRootFromJson(String str) => VarientRoot.fromJson(json.decode(str));

String varientRootToJson(VarientRoot data) => json.encode(data.toJson());

// 对应JSON最外层的根对象
class VarientRoot {
  List<Varient> varients;

  VarientRoot({
    required this.varients,
  });

  factory VarientRoot.fromJson(Map<String, dynamic> json) => VarientRoot(
        varients: List<Varient>.from(json["varients"].map((x) => Varient.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "varients": List<dynamic>.from(varients.map((x) => x.toJson())),
      };
}

// 对应JSON数组里的单个变体对象
class Varient {
  String productId;
  String colour;
  List<String> sizes;
  String image;
  String price;
  String name;
  String retailer;

  Varient({
    required this.productId,
    required this.colour,
    required this.sizes,
    required this.image,
    required this.price,
    required this.name,
    required this.retailer,
  });

  factory Varient.fromJson(Map<String, dynamic> json) => Varient(
        productId: json["ProductId"],
        colour: json["Colour"],
        sizes: List<String>.from(json["Sizes"].map((x) => x)),
        image: json["image"],
        price: json["price"],
        name: json["name"],
        retailer: json["retailer"],
      );

  Map<String, dynamic> toJson() => {
        "ProductId": productId,
        "Colour": colour,
        "Sizes": List<dynamic>.from(sizes.map((x) => x)),
        "image": image,
        "price": price,
        "name": name,
        "retailer": retailer,
      };
}

第二步:修正请求代码的解析逻辑

Future<dynamic> requestProductMonitor() async {
  final product_link = productIDEditingController.text;
  var url = Uri.parse(
      "http://5.226.139.20:8000/getvarient/?url=https://www.prettylittlething.com/mid-blue-wash-long-leg-straight-jeans.html");
  try {
    http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      var jsonResponse = jsonDecode(response.body);
      print("this is the Json Response $jsonResponse");
      
      // 解析根对象,获取变体数组
      VarientRoot root = VarientRoot.fromJson(jsonResponse);
      
      setState(() {
        listModel1.addAll(root.varients);
        // 测试打印变体信息
        if (root.varients.isNotEmpty) {
          print("First varient name: ${root.varients[0].name}");
          print("First varient sizes: ${root.varients[0].sizes}");
        }
      });
      showDropDown();
    } else {
      print("Error: Status code ${response.statusCode}");
    }
  } catch (exp) {
    // 打印具体错误信息,方便排查
    print("Failed, error: ${exp.toString()}");
  }
}

3. 额外建议

  • 在catch块里打印exp.toString(),而不是固定字符串,这样能看到具体错误原因(比如类型不匹配、字段不存在等),更便于排查问题。
  • 如果后续需要添加嵌套对象,只需要在Varient类里添加对应的嵌套类属性,并在fromJson/toJson方法中处理嵌套解析即可。

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 09:52:48