Flutter:如何正确地对`List`进行JSON编码?

问题描述 投票:0回答:1

我正在尝试通过REST API使用Flutter将List传递到我的服务器。

下面是代码

 Future<void> saveOrderItemList(List<OrderItem> orderItems) async {
    int responsetag = 0;
    try {
      await http.post("http://url to post the data",
          body: convert.json.encode(orderItems.toJson()), //This line do not work
          headers: {
            "Accept": "application/json",
            "content-type": "application/json"
          }).then((http.Response response) {
        final int statusCode = response.statusCode;

        print("RESPONSE: " + response.body);
        print("STATUS CODE: " + statusCode.toString());

        if (statusCode < 200 || statusCode > 400 || response.body == null) {
          throw new Exception("Error while fetching data");
        } else {
          responsetag = int.parse(response.body);
        }
      });

      return responsetag;
    } catch (error) {
      throw (error);
    }
  }

以上代码无法运行,因为我无法使用List编码convert.json.encode(orderItems.toJson())

下面是我的OrderItem bean及其序列化类的代码。

part 'order_item.g.dart';

/// An annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated.
@JsonSerializable()
class OrderItem {
  int idorderItem;
  FreshProducts freshProducts;
  Order order;
  ProductSize productSize;
  double orderItemExpectedPricePerKg;
  double orderItemQuantity;
  int dateCreated;
  int lastUpdated;

  OrderItem(
      {
        this.idorderItem,
        this.freshProducts,
        this.order,
        this.productSize,
        this.orderItemExpectedPricePerKg,
        this.orderItemQuantity,
        this.dateCreated,
        this.lastUpdated

      });

  /// A necessary factory constructor for creating a new User instance
  /// from a map. Pass the map to the generated `_$OrderItemFromJson()` constructor.
  /// The constructor is named after the source class, in this case User.
  factory OrderItem.fromJson(Map<String, dynamic> json) => _$OrderItemFromJson(json);

  /// `toJson` is the convention for a class to declare support for serialization
  /// to JSON. The implementation simply calls the private, generated
  /// helper method `_$OrderItemToJson`.
  Map<String, dynamic> toJson() => _$OrderItemToJson(this);
}

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'order_item.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

OrderItem _$OrderItemFromJson(Map<String, dynamic> json) {
  return OrderItem(
    idorderItem: json['idorderItem'] as int,
    freshProducts: json['freshProducts'] == null
        ? null
        : FreshProducts.fromJson(json['freshProducts'] as Map<String, dynamic>),
    order: json['order'] == null
        ? null
        : Order.fromJson(json['order'] as Map<String, dynamic>),
        productSize: json['productSize'] == null
        ? null
        : ProductSize.fromJson(json['productSize'] as Map<String, dynamic>),
    orderItemExpectedPricePerKg:
        (json['orderItemExpectedPricePerKg'] as num)?.toDouble(),
    orderItemQuantity: (json['orderItemQuantity'] as num)?.toDouble(),
    dateCreated: json['dateCreated'] as int,
    lastUpdated: json['lastUpdated'] as int,
  );
}

Map<String, dynamic> _$OrderItemToJson(OrderItem instance) => <String, dynamic>{
      'idorderItem': instance.idorderItem,
      'freshProducts': instance.freshProducts,
      'order': instance.order,
      'productSize': instance.productSize,
      'orderItemExpectedPricePerKg': instance.orderItemExpectedPricePerKg,
      'orderItemQuantity': instance.orderItemQuantity,
      'dateCreated': instance.dateCreated,
      'lastUpdated': instance.lastUpdated,
    };

如何确定我可以将列表从flutter http传递到POST

android ios json http flutter
1个回答
-1
投票

我解决了类似类型的问题。但是我的List被其他键{"data":listOfItemJson}包裹了。所以我首先创建了一个像Mapvar map = {"data": MainOrderController.orderModel.toJson()};,当我发布此uril时,我更新了发布机制,例如:

 var response =
          await http.post(url, headers: headers, body: jsonEncode(map));

注意:jsonEncode()import 'dart:convert';程序包的一部分。

我希望你能得到一个主意

© www.soinside.com 2019 - 2024. All rights reserved.