2017-07-19 267 views
2

我試圖將我的JSON文件映射到一個類對象,然後基於新接收的JSON更新卡片。將JSON映射到類對象

我的JSON結構是這樣的

{ 
     "$class": "FirstCard", 
     "id": "1", 
     "description": "I am card number one", 
     "Role": "attack", 
     "score": 0, 
     "tag": [ 
      "string" 
     ],................} 

我的課是這樣的:

class CardInfo { 
    //Constructor 
    String id; 
    String description; 
    String role; 
    int score; 

} 

我怎麼能在我的JSON文件中的值映射到從CardInfo類創建的對象的字段?

更新

以下試印在ci.description空,這是否意味着該對象從未被創造出來的?

const jsonCodec = const JsonCodec 
_loadData() async { 
    var url = 'myJsonURL'; 
    var httpClient = createHttpClient(); 
    var response =await httpClient.get(url); 
    print ("response" + response.body); 
    Map cardInfo = jsonCodec.decode(response.body); 
    var ci = new CardInfo.fromJson(cardInfo); 
    print (ci.description); //prints null 
} 

UPDATE2

印刷cardInfo給出如下:

{$類:FirstCard,ID:1,描述:我的卡號一個,...... ..}

請注意,它類似於原始的JSON,但沒有字符串值的雙引號。

回答

2
class CardInfo { 
    //Constructor 
    String id; 
    String description; 
    String role; 
    int score; 

    CardInfo.fromJson(Map json) { 
    this.id = json['id']; 
    this.description = json['description']; 
    this.role = json['Role']; 
    this.score = json['score']; 
    } 
} 

var ci = new CardInfo.fromJson(myJson); 

您可以使用源代碼生成工具(如https://github.com/dart-lang/source_gen)爲您生成序列化和反序列化代碼。

如果您更喜歡使用不可變類https://pub.dartlang.org/packages/built_value是一個不錯的選擇。

+0

請檢查我的文章中更新的部分,我嘗試打印對象ci中的一個字段,我得到的全部爲空。 – aziza

+0

'print(cardInfo);'print? –

+0

請在原始文章中查看我的新更新。 – aziza

1

如果你想從一個網址讓你的JSON如下操作:

import 'dart:convert'; 

_toObject() async { 
    var url = 'YourJSONurl'; 
    var httpClient = createHttpClient(); 
    var response =await httpClient.get(url); 
    Map cardInfo = JSON.decode(response.body); 
    var ci = new CardInfo.fromJson(cardInfo); 
} 

請參閱主的答案,如果你想知道如何設置類,以便您的JSON字段可以被映射到它。這非常有幫助。