如何在Dart中将Map <string,dynamic =“”>中的List <map <string,dynamic =“” >>转换为JSON?

时间:2019-02-14 18:36:47

标签: arrays json dart flutter

我正在尝试发送Map<String, dynamic>,而其中一个dynamic实际上是一个List<Map<String, dynamic>>

我这样组装:

Packet packet = Packet(
  datas: stocks.map((stock) => stock.toJson()).toList(),
);

String json = jsonEncode(packet);

问题是发送的实际上是这个:

{
    "datas": {
        "rows": "[{NoArticle: 051131626638, Description: Ruban pour tapis, qty: 5}]"
    }
}

预期输出是:

{
    "datas": {
        "rows": [{
            "NoArticle": "051131626638",
            "Description": "Ruban pour tapis",
            "qty": 5,
        }]
    }
}

我要发送List<Map<String, dynamic>>,而不是String。我该怎么办?

2 个答案:

答案 0 :(得分:0)

答案:我是笨蛋。

我通过一个函数传递了参数,就像这样:

Server.send("sendInventoryBatch", {
  "rows": "${stocks.map((stock) => stock.toJson()).toList()}",
});

当然它将返回一个字符串。

问题无效。如果您有类似的问题,请打开另一个问题。抱歉给您带来不便。


现在,如果有人真的有这个问题并且偶然发现了这个线程,请按以下步骤操作:

  1. 组装您的对象,并确保未在此过程中对其进行字符串化
  2. 使用jsonEncode

如有疑问,请先将所有内容设为Map<String, dynamic>List<dynamic>或二者的子类。

Packet packet = Packet(
  appType: "inventoryManager",
  module: "",
  action: action,
  datas: data,
  deviceID: Globals.map["UUID"],
  cbackid: cback,
);

您可以使用多个在线资源从JSON生成类似我的自定义Packet的类,因为jsonEncode将使用自动生成的Map<String, dynamic> toJson()

String json = jsonEncode(packet);

瞧,您完成了。

答案 1 :(得分:-1)

您看过软件包json_serializable吗? 这是一个Person有许多Order的示例:example

    // Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
    // for details. All rights reserved. Use of this source code is governed by a
    // BSD-style license that can be found in the LICENSE file.

    import 'package:json_annotation/json_annotation.dart';

    part 'example.g.dart';

    @JsonSerializable()
    class Person {
      final String firstName;
      @JsonKey(includeIfNull: false)
      final String middleName;
      final String lastName;

      @JsonKey(name: 'date-of-birth', nullable: false)
      final DateTime dateOfBirth;

      @JsonKey(name: 'last-order')
      final DateTime lastOrder;

      @JsonKey(nullable: false)
      List<Order> orders;

      Person(this.firstName, this.lastName, this.dateOfBirth,
          {this.middleName, this.lastOrder, List<Order> orders})
          : orders = orders ?? <Order>[];

      factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

      Map<String, dynamic> toJson() => _$PersonToJson(this);
    }

    @JsonSerializable(includeIfNull: false)
    class Order {
      int count;
      int itemNumber;
      bool isRushed;
      Item item;

      @JsonKey(
          name: 'prep-time',
          fromJson: _durationFromMilliseconds,
          toJson: _durationToMilliseconds)
      Duration prepTime;

      @JsonKey(fromJson: _dateTimeFromEpochUs, toJson: _dateTimeToEpochUs)
      final DateTime date;

      Order(this.date);

      factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);

      Map<String, dynamic> toJson() => _$OrderToJson(this);

      static Duration _durationFromMilliseconds(int milliseconds) =>
          Duration(milliseconds: milliseconds);

      static int _durationToMilliseconds(Duration duration) =>
          duration.inMilliseconds;

      static DateTime _dateTimeFromEpochUs(int us) =>
          DateTime.fromMicrosecondsSinceEpoch(us);

      static int _dateTimeToEpochUs(DateTime dateTime) =>
          dateTime.microsecondsSinceEpoch;
    }

    @JsonSerializable()
    class Item {
      int count;
      int itemNumber;
      bool isRushed;

      Item();

      factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);

      Map<String, dynamic> toJson() => _$ItemToJson(this);
    }

    @JsonLiteral('data.json')
    Map get glossaryData => _$glossaryDataJsonLiteral;