天天看點

json 在 Flutter(Dart)中的使用

首先準備好json資料

//一個JSON格式的使用者清單字元串
String jsonStr = '[{"name":"Jack"},{"name":"Rose"}]';
//
String jsonStr1 = '{"name": "John Smith","email": "[email protected]"}';
           

第一種方式:使用集合來操作資料

導入 

import 'dart:convert';
使用 json.decode()将JSON字元串轉為集合對象
    json.encode()将集合對象轉為JSON字元串
           
//将JSON字元串轉為Dart對象(此處是List)
List items = json.decode(jsonStr);
//輸出第一個使用者的姓名
print(items[0]["name"]);

//Json字元串轉Map類型
Map userMap = json.decode(jsonStr1);
print(userMap);

//Map轉Json字元串
print(json.encode(userMap));
           

結果:

json 在 Flutter(Dart)中的使用

可以看到,Map類型是不帶 雙引号的

第二種方式:使用 Model class 操作資料

方法一:自定義 Model ,隻是為了弄懂記錄一下,不建議實際使用

首先準備好資料:使用上面的 jsonStr1

String jsonStr1 = '{"name": "John Smith","email": "[email protected]"}';

//Json字元串轉Map類型
Map userMap = json.decode(jsonStr1);
           

現在針對這個Map 我們自定義一個 Model類:User

class User {
  String name;
  String email;

  User(this.name, this.email);

  // 把 Map 轉為 User 類
  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  // 通過User屬性,傳回一個Map
  Map<String, dynamic> toJson() =>
      <String, dynamic>{
        'name': name,
        'email': email,
      };
}
           

使用:

var user = User.fromJson(userMap);
print(user.name);
user.name = "Bob";
// 這裡隻是把 User 轉換 為 Map
print(user.toJson());
// 要 json 格式字元串 還需要使用 json.encode()
print(json.encode(user.toJson()));
           

結果:

json 在 Flutter(Dart)中的使用

方法二:使用 插件 FlutterJsonBeanFactory 自動生成 Model class

json 在 Flutter(Dart)中的使用

準備資料:

var webInfo = {
  "name":"網站",
  "num":3,
  "sites": [
    { "name":"Google", "info":[ "Android", "Google 搜尋", "Google 翻譯" ] },
    { "name":"Runoob", "info":[ "菜鳥教程", "菜鳥工具", "菜鳥微信" ] },
    { "name":"Taobao", "info":[ "淘寶", "網購" ] }
  ]
};
           

生成 Model 類(這裡不好截圖)

new -> JsonToDartBeanAction,出現:

json 在 Flutter(Dart)中的使用

Make後得到 Model 類:

class WebInfoEntity {
	int num;
	String name;
	List<WebInfoSite> sites;

	WebInfoEntity({this.num, this.name, this.sites});

	WebInfoEntity.fromJson(Map<String, dynamic> json) {
		num = json['num'];
		name = json['name'];
		if (json['sites'] != null) {
			sites = new List<WebInfoSite>();(json['sites'] as List).forEach((v) { sites.add(new WebInfoSite.fromJson(v)); });
		}
	}

	Map<String, dynamic> toJson() {
		final Map<String, dynamic> data = new Map<String, dynamic>();
		data['num'] = this.num;
		data['name'] = this.name;
		if (this.sites != null) {
      data['sites'] =  this.sites.map((v) => v.toJson()).toList();
    }
		return data;
	}
}

class WebInfoSite {
	String name;
	List<String> info;

	WebInfoSite({this.name, this.info});

	WebInfoSite.fromJson(Map<String, dynamic> json) {
		name = json['name'];
		info = json['info']?.cast<String>();
	}

	Map<String, dynamic> toJson() {
		final Map<String, dynamic> data = new Map<String, dynamic>();
		data['name'] = this.name;
		data['info'] = this.info;
		return data;
	}
}
           

現在可以使用了:

// 把 json 資料 轉換為 WebInfoEntity 類
var w = WebInfoEntity.fromJson(webInfo);
print(w.sites[0].info[2]);
w.sites[0].info[2] = "tianmao";
print(w.toJson()); //Map
           

結果:

json 在 Flutter(Dart)中的使用

第三種方式:實際從網絡擷取json資料,并對資料進行操作(集合類型資料)

使用 dio 擷取 json 資料

準備資料:

// 傳回 json 字元串的網址
final String apiUrl1 = "http://a.itying.com/api/productlist";
           

使用:

Dio dio = Dio();
  //  通過 dio get 資料
  Future _getDio() async {
    Response response = await dio.get(apiUrl1);
    print('get --- '+response.data.toString());
    print(response.data.runtimeType);
    print(response.data["result"][0]['title']);
 }
           

結果:

json 在 Flutter(Dart)中的使用

這個 dio 傳回後的資料直接就是 集合類型了,可以直接操作(就不需要使用json.decode()了)

具體傳回什麼類型的集合,是 dio 根據 json 格式自動判定的,

使用的時候可以先通過 print(response.data.runtimeType); 檢視類型,

再決定是直接操作,還是轉換為 Model 類

 實際應用場景:可以配合 ListView來展示資料等

json 在 Flutter(Dart)中的使用