Flutter:JSON无键数组到列表

Posted

技术标签:

【中文标题】Flutter:JSON无键数组到列表【英文标题】:Flutter : JSON Keyless array to List 【发布时间】:2021-01-14 14:46:43 【问题描述】:

我需要将一个 array(JSON 格式)的 php 响应加载到 Flutter List。如何在 Flutter 中编写代码?我应该使用 dart convert 吗?

这是我的 PHP 响应:

[
    "Butter",
    "Cheese / Keju",
    "Cream",
    "Fresh Juice",
    "Frozen Food Beef",
    "Frozen Food Chicken",
    "Frozen Food Pork",
    "Frozen Food Potatoes",
    "Frozen Food Vegetables",
    "Jam & Spread",
    "Mayonais",
    "Salad Dressing",
    "Sereal & Muesli",
    "Snack & Biscuit",
    "Sour Cream",
    "Soya Milk",
    "Whipping Cream",
    "Yogurt",
    "Yogurt Drink"
]

【问题讨论】:

参考:medium.com/flutter-community/… 【参考方案1】:

超级简单。只需使用基本的json 库。

import 'dart:convert';

// assume you got this string from a php request
String fromPhp = '[ "Butter", "Cheese / Keju", "Cream", "Fresh Juice", "Frozen Food Beef", "Frozen Food Chicken", "Frozen Food Pork", "Frozen Food Potatoes", "Frozen Food Vegetables", "Jam & Spread", "Mayonais", "Salad Dressing", "Sereal & Muesli", "Snack & Biscuit", "Sour Cream", "Soya Milk", "Whipping Cream", "Yogurt", "Yogurt Drink" ]';

// use this to convert it to a dart list of string
// note that the only tricky part is that json.decode will return
// a List<dynamic> so I am using List.from to convert it to List<String> 
List<String> dartList = List.from(json.decode(fromPhp));
print(dartList);

【讨论】:

以上是关于Flutter:JSON无键数组到列表的主要内容,如果未能解决你的问题,请参考以下文章

60 无键值Json数组和有键值json数组实验

PHP json转换 无键名数据格式转换为有键名格式

Flutter - 解析多个 json 数组并设置为列表

flutter : 嵌套的 json 解析列表

Flutter - 提取到 FutureBuilder 的 JSON 反序列化数据返回空值

json 地理排行榜测试无键