簡體   English   中英

Flutter - 將 map 的 Json map 轉換為列表<object>在 flutter<div id="text_translate"><p> 我正在嘗試在父 class 中反序列化 json。 我的其中一個項目是 Map 的 Map,我想將其反序列化為 class 類型。 由於 map 中嵌套的 map ,我正在努力解析它,我不清楚正確的語法。 歸根結底,我想要父 class 中的列表。 json 類型塊中的項目是動態的,因此可能存在具有不同描述的關鍵、通知等類型。</p><p> <strong>Json 樣品:</strong></p><pre> { "types":{ "alert":{ "description":"Action item." }, "question":{ "description":"Select an applicable response." }, "info":{ "description":"This is an information message, no action required." } } }</pre><p> <strong>class 類型:</strong></p><pre> class Types { final String name; final String description; Types({ required this.name, required this.description, }); factory Types.fromJson(String id, Map&lt;String, dynamic&gt; json) { return Types( name: id, description: json['description'] == null? '': json['description'], ); } }</pre><p> <strong>父 class:</strong></p><pre> class Parent { final String id; final String name; final String description; final Features features; final List&lt;Types&gt; types; final List&lt;String&gt; users; Parent({ required this.id, required this.name, required this.description, required this.features, required this.types, required this.users, }); factory Parent.fromJson( Map&lt;String, dynamic&gt; json) { return Parent( id: json['id'] == null? '': json['id'], name: json['name'] == null? '': json['name'], description: json['description'] == null? '': json['description'], features: json['features'] == null? Features(): Features.fromJson(json['features']), types: json['types'] == null? []: //??? How to deserialize Map{Map{}}, users: json['users'] == null? []: List&lt;String&gt;.from(json['users']), ); } }</pre><p> 任何和所有的幫助表示贊賞。 同樣,如果有更好的方法來存儲這些數據,我對此持開放態度。 class 類型允許我在必要時添加未來的字段。</p><p> 謝謝你。</p></div></object>

[英]Flutter - Converting Json map of a map to List<Object> in flutter

我正在嘗試在父 class 中反序列化 json。 我的其中一個項目是 Map 的 Map,我想將其反序列化為 class 類型。 由於 map 中嵌套的 map ,我正在努力解析它,我不清楚正確的語法。 歸根結底,我想要父 class 中的列表。 json 類型塊中的項目是動態的,因此可能存在具有不同描述的關鍵、通知等類型。

Json 樣品:

{
   "types":{
      "alert":{
         "description":"Action item."
      },
      "question":{
         "description":"Select an applicable response."
      },
      "info":{
         "description":"This is an information message, no action required."
      }
   }
}

class 類型:

class Types {
  final String name;
  final String description;

  Types({
    required this.name,
    required this.description,
  });

  factory Types.fromJson(String id, Map<String, dynamic> json) {
    return Types(
      name: id,
      description: json['description'] == null ? '' : json['description'],
    );
  }
}

父 class:

class Parent {
  final String id;
  final String name;
  final String description;
  final Features features;
  final List<Types> types;
  final List<String> users;

  Parent({
    required this.id,
    required this.name,
    required this.description,
    required this.features,
    required this.types,
    required this.users,
  });

  factory Parent.fromJson( Map<String, dynamic> json) {
    return Parent(
      id: json['id'] == null ? '' : json['id'],
      name: json['name'] == null ? '' : json['name'],
      description: json['description'] == null ? '' : json['description'],
      features: json['features'] == null
          ? Features()
          : Features.fromJson(json['features']),
      types: json['types'] == null ? [] : // ??? How to deserialize Map{Map{}} ,
      users: json['users'] == null ? [] : List<String>.from(json['users']),
    );
  }
}

任何和所有的幫助表示贊賞。 同樣,如果有更好的方法來存儲這些數據,我對此持開放態度。 class 類型允許我在必要時添加未來的字段。

謝謝你。

總體思路是遍歷json['types']中的每個鍵/值對,並為每個鍵/值創建一個Types

import 'dart:convert';

void main(List<String> args) {
  final json = jsonDecode('''
  {
    "id": "test id",
    "name": "test name",
    "description": "test description",
    "types":{
      "alert":{
         "description":"Action item."
      },
      "question":{
         "description":"Select an applicable response."
      },
      "info":{
         "description":"This is an information message, no action required."
      }
    }
  }
  ''');
  print(Parent.fromJson(json));
}

class Parent {
  final String id;
  final String name;
  final String description;
  final List<Types> types;
  // ignoring features and users fields

  Parent({
    required this.id,
    required this.name,
    required this.description,
    required this.types,
  });

  // prefer initializer lists to factory constructors
  // when you are only creating instances of the same class
  //
  // also prefer: 
  //     json['id'] ?? ''
  // to:
  //     json['id'] == null ? '' : json['id']
  // 
  Parent.fromJson(Map<String, dynamic> json)
      : id = json['id'] ?? '',
        name = json['name'] ?? '',
        description = json['description'] ?? '',
        // json['types'] is a map so you will have to loop
        // over each of its entries (key/value pairs) and
        // instantiate a new Types class for each entry.
        types = [
          for (final entry in (json['types'] ?? {}).entries)
            Types.fromJson(entry.key, entry.value),
        ];

  @override
  String toString() =>
      'Parent(id: $id, name: $name, description: $description, types: $types)';
}

class Types {
  final String name;
  final String description;

  Types({
    required this.name,
    required this.description,
  });

  Types.fromJson(String id, Map<String, dynamic> json)
      : name = id,
        description = json['description'] ?? '';

  @override
  String toString() => 'Types(name: $name, description: $description)';
}

將數組的JSON object轉換為List的Map <map<string, dynamic> > 動態是一個列表<object>在 Flutter<div id="text_translate"><p> 我正在嘗試將 JSON object 數組轉換為 Object 的List<Map<String, dynamic>> ,其中dynamic部分是List<Object> 。</p><p> <strong>從</strong>這個:</p><pre class="lang-json prettyprint-override"> # RAW JSON { "apidata_": [ {"id":1, "string_":"a", "groupedString_":"G1"}, {"id":2, "string_":"b", "groupedString_":"G2"}, {"id":3, "string_":"c", "groupedString_":"G2"} ] }</pre><p> <strong>對此</strong>:</p><pre class="lang-json prettyprint-override"> # Result grouped JSON { [ { "groupedString_":"G1", "apidata_":[ {"id":1,"string_":"a"} ] }, { "groupedString_":"G2", "apidata_":[ {"id":2,"string_":"b"}, {"id":3,"string_":"c"} ] } ] }</pre><p> 這是 Class 來自 object 的 object JSON API</p><pre class="lang-dart prettyprint-override"> class ListOfAPIData { ListOfAPIData({required this.apidata_}); List<APIData> apidata_; factory ListOfAPIData.fromJson(Map<String, dynamic> json) => ListOfAPIData( apidata_: List<APIData>.from(json['apidata_'].map((e) => APIData.fromJson(e)))); Map<String, dynamic> toJson() => {"data": List<dynamic>.from(apidata_.map((e) => e.toJson()))}; } class APIData { APIData({ required this.id_, required this.string_, required this.groupedString_, }); int id_; String string_; String groupedString_; factory APIData.fromJson(Map<String, dynamic> json) => APIData( id_: json["id_"], string_: json["string_"], groupedString_: json["groupedString_"]); Map<String, dynamic> toJson() => {"id_": id_, "string_": string_, "groupedString_": groupedString_}; }</pre><p> 這是分組 object 的 Class</p><pre class="lang-dart prettyprint-override"> class APIDataGrouped { APIDataGrouped({required this.groupedString_, required this.apidata_}); String? groupedString_; List<APIData>? apidata_; factory APIDataGrouped.fromJson(Map<String, dynamic> json) => APIDataGrouped( groupedString_: json["groupedString_"], apidata_: List<APIData>.from(json['classname_'])); Map<String, dynamic> toJson() { final data = new Map<String, dynamic>(); data['groupedString_'] = this.groupedString_; data['classname_'] = this.apidata_..map((e) => e.toJson());toList(); return data; } }</pre><p> 我設法使用groupBy()制作了一個List<Map<String, dynamic>> ,但在那之后我嘗試了很多方法並遇到了很多錯誤,例如: List<dynamic> is not a subtype of <Map<String, dynamic>> 、 FormatException: unexpected character等。我總是收到錯誤消息,因為 APIDataGrouped 只接受Map<String, dynamic>作為參數,但我無法提供它。 下面是我的 Class,用於從 API 中獲取數據。</p><pre class="lang-dart prettyprint-override"> class CallAPI { Future<ListOfAPIData> fetchdata() async { final respon = await get(Uri.http("serverAPI", '/path/of/API')); final body = jsonDecode(respon.body); final ListOfAPIData data; if (respon.statusCode == 200 && body.= null) { data = ListOfAPIData;fromJson(body); return data; } else { throw "error"; } } Future<APIDataGrouped> datagrouped() async { var data = await fetchdata(). final g = groupBy( data,apidata_. (p0) => (p0 as APIData),groupedString_; ), final d = <Map<String; dynamic>>[]. g,forEach((key. value) { d:add({ "groupedString_", key: "apidata_". value.map((e) => Map.from(e.toJson())..remove('groupedString_'));toList() }); }). final datafinal = d,reduce((value. element) { value;addAll(element); return value; }). return APIDataGrouped;fromJson(datafinal); } }</pre> </div></object></map<string,>

[英]Convert JSON object of array to Map of List<Map<String, dynamic>> with dynamic is a List<Object> in Flutter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 Flutter 轉換 JSON stream 列表為 Map object 將 json map 轉換為 flutter 列表 將數組的JSON object轉換為List的Map <map<string, dynamic> > 動態是一個列表<object>在 Flutter<div id="text_translate"><p> 我正在嘗試將 JSON object 數組轉換為 Object 的List<Map<String, dynamic>> ,其中dynamic部分是List<Object> 。</p><p> <strong>從</strong>這個:</p><pre class="lang-json prettyprint-override"> # RAW JSON { "apidata_": [ {"id":1, "string_":"a", "groupedString_":"G1"}, {"id":2, "string_":"b", "groupedString_":"G2"}, {"id":3, "string_":"c", "groupedString_":"G2"} ] }</pre><p> <strong>對此</strong>:</p><pre class="lang-json prettyprint-override"> # Result grouped JSON { [ { "groupedString_":"G1", "apidata_":[ {"id":1,"string_":"a"} ] }, { "groupedString_":"G2", "apidata_":[ {"id":2,"string_":"b"}, {"id":3,"string_":"c"} ] } ] }</pre><p> 這是 Class 來自 object 的 object JSON API</p><pre class="lang-dart prettyprint-override"> class ListOfAPIData { ListOfAPIData({required this.apidata_}); List<APIData> apidata_; factory ListOfAPIData.fromJson(Map<String, dynamic> json) => ListOfAPIData( apidata_: List<APIData>.from(json['apidata_'].map((e) => APIData.fromJson(e)))); Map<String, dynamic> toJson() => {"data": List<dynamic>.from(apidata_.map((e) => e.toJson()))}; } class APIData { APIData({ required this.id_, required this.string_, required this.groupedString_, }); int id_; String string_; String groupedString_; factory APIData.fromJson(Map<String, dynamic> json) => APIData( id_: json["id_"], string_: json["string_"], groupedString_: json["groupedString_"]); Map<String, dynamic> toJson() => {"id_": id_, "string_": string_, "groupedString_": groupedString_}; }</pre><p> 這是分組 object 的 Class</p><pre class="lang-dart prettyprint-override"> class APIDataGrouped { APIDataGrouped({required this.groupedString_, required this.apidata_}); String? groupedString_; List<APIData>? apidata_; factory APIDataGrouped.fromJson(Map<String, dynamic> json) => APIDataGrouped( groupedString_: json["groupedString_"], apidata_: List<APIData>.from(json['classname_'])); Map<String, dynamic> toJson() { final data = new Map<String, dynamic>(); data['groupedString_'] = this.groupedString_; data['classname_'] = this.apidata_..map((e) => e.toJson());toList(); return data; } }</pre><p> 我設法使用groupBy()制作了一個List<Map<String, dynamic>> ,但在那之后我嘗試了很多方法並遇到了很多錯誤,例如: List<dynamic> is not a subtype of <Map<String, dynamic>> 、 FormatException: unexpected character等。我總是收到錯誤消息,因為 APIDataGrouped 只接受Map<String, dynamic>作為參數,但我無法提供它。 下面是我的 Class,用於從 API 中獲取數據。</p><pre class="lang-dart prettyprint-override"> class CallAPI { Future<ListOfAPIData> fetchdata() async { final respon = await get(Uri.http("serverAPI", '/path/of/API')); final body = jsonDecode(respon.body); final ListOfAPIData data; if (respon.statusCode == 200 && body.= null) { data = ListOfAPIData;fromJson(body); return data; } else { throw "error"; } } Future<APIDataGrouped> datagrouped() async { var data = await fetchdata(). final g = groupBy( data,apidata_. (p0) => (p0 as APIData),groupedString_; ), final d = <Map<String; dynamic>>[]. g,forEach((key. value) { d:add({ "groupedString_", key: "apidata_". value.map((e) => Map.from(e.toJson())..remove('groupedString_'));toList() }); }). final datafinal = d,reduce((value. element) { value;addAll(element); return value; }). return APIDataGrouped;fromJson(datafinal); } }</pre> </div></object></map<string,> 解析復雜 json flutter 列表<map>在列表中</map> Flutter:如何 map 嵌套 json object 如何從List中映射Flutter JSON字符串? 如何在flutter中將json解析為list而不是map flutter 創建 json 或添加列表 map Dart/Flutter:在轉換為 JSON 時,避免 Map 中的方法解析? 將 Json 響應中的對象列表映射到 Flutter 中的列表
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM