如何在dart flutter中将json字符串转换为json对象?

时间:2019-03-22 03:49:58

标签: json dart flutter

我有这样的字符串,

{id:1, name: lorem ipsum, address: dolor set amet}

我需要将该字符串转换为json,如何在dart flutter中实现呢?非常感谢您的帮助。

5 个答案:

答案 0 :(得分:0)

您必须导入dart:encode库。然后使用jsonDecode函数,该函数将产生类似于Map的动态

https://api.dartlang.org/stable/2.2.0/dart-convert/dart-convert-library.html

答案 1 :(得分:0)

您必须使用json.decode。它接受一个json对象,并让您处理嵌套的键值对。我给你写个例子

// 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};
}

答案 2 :(得分:0)

您还可以将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;
  }
}

答案 3 :(得分:0)

您有时必须使用此

Map<String, dynamic> toJson() {
  return {
    jsonEncode("phone"): jsonEncode(numberPhone),
    jsonEncode("country"): jsonEncode(country),

 };
}

此代码为您提供一个类似的字符串 {“ numberPhone”:“ + 225657869”,“ country”:“ CI”} 。这样就很容易解码了

     json.decode({"numberPhone":"+22565786589", "country":"CI"})

答案 4 :(得分:0)

假设我们有一个简单的JSON结构,如下所示:

{
  "name": "bezkoder",
  "age": 30
}

我们将创建一个名为User的Dart类,其字段为:nameage

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 库的内置jsonDecode()函数。

import 'dart:convert';

main() {
  String objText = '{"name": "bezkoder", "age": 30}';

  User user = User.fromJson(jsonDecode(objText));

  print(user);

结果将如下所示。

{ bezkoder, 30 }

Ref:Dart/Flutter parse JSON string into Object