當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Dart jsonEncode用法及代碼示例

dart:convert 庫中jsonEncode 函數的用法介紹如下。

用法:

String jsonEncode(
   Object? object,    
   {Object? toEncodable(
   Object? nonEncodable   
)?}   
)

object 轉換為 JSON 字符串。

如果 value 包含不能直接編碼為 JSON 字符串的對象(不是數字、布爾值、字符串、null、列表或帶有字符串鍵的映射的值),則使用 toEncodable 函數將其轉換為對象必須是可直接編碼的。

如果省略toEncodable,則默認為返回在不可編碼對象上調用.toJson() 的結果的函數。

json.encode 的簡寫。如果局部變量隱藏全局 json 常量,則很有用。

例子:

const data = {'text': 'foo', 'value': 2, 'status': false, 'extra': null};
final String jsonString = jsonEncode(data);
print(jsonString); // {"text":"foo","value":2,"status":false,"extra":null}

將原本不受支持的對象轉換為自定義 JSON 格式的示例:

class CustomClass {
  final String text;
  final int value;
  CustomClass({required this.text, required this.value});
  CustomClass.fromJson(Map<String, dynamic> json)
      : text = json['text'],
        value = json['value'];

  static Map<String, dynamic> toJson(CustomClass value) =>
      {'text': value.text, 'value': value.value};
}

void main() {
  final CustomClass cc = CustomClass(text: 'Dart', value: 123);
  final jsonText = jsonEncode({'cc': cc},
      toEncodable: (Object? value) => value is CustomClass
          ? CustomClass.toJson(value)
          : throw UnsupportedError('Cannot convert to JSON: $value'));
  print(jsonText); // {"cc":{"text":"Dart","value":123}}
}

相關用法


注:本文由純淨天空篩選整理自dart.dev大神的英文原創作品 jsonEncode function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。