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 jsonDecode用法及代碼示例
- Dart MapMixin.containsKey用法及代碼示例
- Dart Iterator用法及代碼示例
- Dart AttributeClassSet.intersection用法及代碼示例
- Dart num.sign用法及代碼示例
- Dart TransformList.last用法及代碼示例
- Dart FileList.first用法及代碼示例
- Dart CanvasRenderingContext2D.drawImageScaledFromSource用法及代碼示例
- Dart FileList.length用法及代碼示例
- Dart Iterable.takeWhile用法及代碼示例
- Dart LinkedHashMap用法及代碼示例
- Dart RegExp.pattern用法及代碼示例
- Dart StreamTransformer構造函數用法及代碼示例
- Dart JsArray.removeAt用法及代碼示例
- Dart ListMixin.expand用法及代碼示例
- Dart UriData.parse用法及代碼示例
- Dart Point用法及代碼示例
- Dart Int32x4List.view用法及代碼示例
- Dart Uri.decodeFull用法及代碼示例
- Dart Future用法及代碼示例
- Dart File用法及代碼示例
- Dart ObjectStore.openCursor用法及代碼示例
- Dart Process用法及代碼示例
- Dart Uri.replace用法及代碼示例
- Dart LengthList.first用法及代碼示例
注:本文由純淨天空篩選整理自dart.dev大神的英文原創作品 jsonEncode function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。