如何在 dart flutter 中将 json 字符串转换为 json 对象?
how to convert json string to json object in dart flutter?
我有这样的字符串,
{id:1, name: lorem ipsum, address: dolor set amet}
而且我需要将该字符串转换为 json,如何在 dart flutter 中完成?非常感谢您的帮助。
您必须导入 dart:encode 库。然后使用 jsonDecode 函数,这将产生类似于 Map
的动态
https://api.dartlang.org/stable/2.2.0/dart-convert/dart-convert-library.html
您必须使用 json.decode
。它接收一个 json 对象并让您处理嵌套的键值对。我给你写个例子
import 'dart:convert';
// actual data sent is {success: true, data:{token:'token'}}
final response = await client.post(url, body: reqBody);
// Notice how you have to call body from the response if you are using http to retrieve json
final body = json.decode(response.body);
// This is how you get success value out of the actual json
if (body['success']) {
//Token is nested inside data field so it goes one deeper.
final String token = body['data']['token'];
return {"success": true, "token": token};
}
您还可以将 JSON 数组转换为对象列表,如下所示:
String jsonStr = yourMethodThatReturnsJsonText();
Map<String,dynamic> d = json.decode(jsonStr.trim());
List<MyModel> list = List<MyModel>.from(d['jsonArrayName'].map((x) => MyModel.fromJson(x)));
而MyModel
是这样的:
class MyModel{
String name;
int age;
MyModel({this.name,this.age});
MyModel.fromJson(Map<String, dynamic> json) {
name= json['name'];
age= json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
return data;
}
}
你有时肯定需要用到这个
Map<String, dynamic> toJson() {
return {
jsonEncode("phone"): jsonEncode(numberPhone),
jsonEncode("country"): jsonEncode(country),
};
}
此代码给你一个喜欢的字符串 {"numberPhone":"+225657869", "country":"CI"}。这样就很容易解码了
json.decode({"numberPhone":"+22565786589", "country":"CI"})
假设我们有一个像这样的简单 JSON 结构:
{
"name": "bezkoder",
"age": 30
}
我们将创建一个名为 User
的 Dart class,其字段为:name
& age
.
class User {
String name;
int age;
User(this.name, this.age);
factory User.fromJson(dynamic json) {
return User(json['name'] as String, json['age'] as int);
}
@override
String toString() {
return '{ ${this.name}, ${this.age} }';
}
}
你可以在上面的代码中看到factory User.fromJson()
方法。它将动态对象解析为 User
对象。那么如何从 JSON 字符串中获取 dynamic
对象呢?
我们使用 dart:convert 库的 built-in jsonDecode()
函数。
import 'dart:convert';
main() {
String objText = '{"name": "bezkoder", "age": 30}';
User user = User.fromJson(jsonDecode(objText));
print(user);
结果将如下所示。
{ bezkoder, 30 }
String name = "{click_action: FLUTTER_NOTIFICATION_CLICK, sendByImage: https://ujjwalchef.staging-server.in/uploads/users/1636620532.png, status: done, sendByName: mohittttt, id: HM11}";
List<String> str = name.replaceAll("{","").replaceAll("}","").split(",");
Map<String,dynamic> result = {};
for(int i=0;i<str.length;i++){
List<String> s = str[i].split(":");
result.putIfAbsent(s[0].trim(), () => s[1].trim());
}
print(result);
}
为了将字符串转换为JSON,我们必须使用自定义逻辑对其进行修改,在这里我们首先删除数组和对象的所有符号,然后我们用特殊字符拆分文本并附加键和值(对于地图)。
请在 dartpad.dev
中尝试此代码片段
import 'dart:developer';
void main() {
String stringJson = '[{product_id: 1, quantity: 1, price: 16.5}]';
stringJson = removeJsonAndArray(stringJson);
var dataSp = stringJson.split(',');
Map<String, String> mapData = {};
for (var element in dataSp) {
mapData[element.split(':')[0].trim()] = element.split(':')[1].trim();
}
print("jsonInModel: ${DemoModel.fromJson(mapData).toJson()}");
}
String removeJsonAndArray(String text) {
if (text.startsWith('[') || text.startsWith('{')) {
text = text.substring(1, text.length - 1);
if (text.startsWith('[') || text.startsWith('{')) {
text = removeJsonAndArray(text);
}
}
return text;
}
class DemoModel {
String? productId;
String? quantity;
String? price;
DemoModel({this.productId, this.quantity, this.price});
DemoModel.fromJson(Map<String, dynamic> json) {
log('json: ${json['product_id']}');
productId = json['product_id'];
quantity = json['quantity'];
price = json['price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['product_id'] = productId;
data['quantity'] = quantity;
data['price'] = price;
return data;
}
}
我有这样的字符串,
{id:1, name: lorem ipsum, address: dolor set amet}
而且我需要将该字符串转换为 json,如何在 dart flutter 中完成?非常感谢您的帮助。
您必须导入 dart:encode 库。然后使用 jsonDecode 函数,这将产生类似于 Map
的动态https://api.dartlang.org/stable/2.2.0/dart-convert/dart-convert-library.html
您必须使用 json.decode
。它接收一个 json 对象并让您处理嵌套的键值对。我给你写个例子
import 'dart:convert';
// actual data sent is {success: true, data:{token:'token'}}
final response = await client.post(url, body: reqBody);
// Notice how you have to call body from the response if you are using http to retrieve json
final body = json.decode(response.body);
// This is how you get success value out of the actual json
if (body['success']) {
//Token is nested inside data field so it goes one deeper.
final String token = body['data']['token'];
return {"success": true, "token": token};
}
您还可以将 JSON 数组转换为对象列表,如下所示:
String jsonStr = yourMethodThatReturnsJsonText();
Map<String,dynamic> d = json.decode(jsonStr.trim());
List<MyModel> list = List<MyModel>.from(d['jsonArrayName'].map((x) => MyModel.fromJson(x)));
而MyModel
是这样的:
class MyModel{
String name;
int age;
MyModel({this.name,this.age});
MyModel.fromJson(Map<String, dynamic> json) {
name= json['name'];
age= json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
return data;
}
}
你有时肯定需要用到这个
Map<String, dynamic> toJson() {
return {
jsonEncode("phone"): jsonEncode(numberPhone),
jsonEncode("country"): jsonEncode(country),
};
}
此代码给你一个喜欢的字符串 {"numberPhone":"+225657869", "country":"CI"}。这样就很容易解码了
json.decode({"numberPhone":"+22565786589", "country":"CI"})
假设我们有一个像这样的简单 JSON 结构:
{
"name": "bezkoder",
"age": 30
}
我们将创建一个名为 User
的 Dart class,其字段为:name
& age
.
class User {
String name;
int age;
User(this.name, this.age);
factory User.fromJson(dynamic json) {
return User(json['name'] as String, json['age'] as int);
}
@override
String toString() {
return '{ ${this.name}, ${this.age} }';
}
}
你可以在上面的代码中看到factory User.fromJson()
方法。它将动态对象解析为 User
对象。那么如何从 JSON 字符串中获取 dynamic
对象呢?
我们使用 dart:convert 库的 built-in jsonDecode()
函数。
import 'dart:convert';
main() {
String objText = '{"name": "bezkoder", "age": 30}';
User user = User.fromJson(jsonDecode(objText));
print(user);
结果将如下所示。
{ bezkoder, 30 }
String name = "{click_action: FLUTTER_NOTIFICATION_CLICK, sendByImage: https://ujjwalchef.staging-server.in/uploads/users/1636620532.png, status: done, sendByName: mohittttt, id: HM11}";
List<String> str = name.replaceAll("{","").replaceAll("}","").split(",");
Map<String,dynamic> result = {};
for(int i=0;i<str.length;i++){
List<String> s = str[i].split(":");
result.putIfAbsent(s[0].trim(), () => s[1].trim());
}
print(result);
}
为了将字符串转换为JSON,我们必须使用自定义逻辑对其进行修改,在这里我们首先删除数组和对象的所有符号,然后我们用特殊字符拆分文本并附加键和值(对于地图)。 请在 dartpad.dev
中尝试此代码片段import 'dart:developer';
void main() {
String stringJson = '[{product_id: 1, quantity: 1, price: 16.5}]';
stringJson = removeJsonAndArray(stringJson);
var dataSp = stringJson.split(',');
Map<String, String> mapData = {};
for (var element in dataSp) {
mapData[element.split(':')[0].trim()] = element.split(':')[1].trim();
}
print("jsonInModel: ${DemoModel.fromJson(mapData).toJson()}");
}
String removeJsonAndArray(String text) {
if (text.startsWith('[') || text.startsWith('{')) {
text = text.substring(1, text.length - 1);
if (text.startsWith('[') || text.startsWith('{')) {
text = removeJsonAndArray(text);
}
}
return text;
}
class DemoModel {
String? productId;
String? quantity;
String? price;
DemoModel({this.productId, this.quantity, this.price});
DemoModel.fromJson(Map<String, dynamic> json) {
log('json: ${json['product_id']}');
productId = json['product_id'];
quantity = json['quantity'];
price = json['price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['product_id'] = productId;
data['quantity'] = quantity;
data['price'] = price;
return data;
}
}