2015-05-19 24 views
1

此問題與this發佈。如何在飛鏢中創建json可編碼類

我嘗試下面的代碼:

import 'dart:convert'; 

/*server side Post class */ 
class Post { 
    int post_id; 
    String title; 
    String description; 
    DateTime posted_at; 
    DateTime last_edited; 
    String user; 
    String editor; 
    int up_votes; 
    int down_votes; 
    int total_votes; 
    String links_to; 
    List<String> tags = new List(); 

    Post.fromSQL(List sql_post) { 
    //initialization code, unrelated. 
    } 

    Map toJson(){ 
    Map fromObject = { 
     'post_id' : post_id, 
     'title' : title, 
     'description' : description, 
     'posted_at' : posted_at, 
     'last_edited' : last_edited, 
     'user' : user, 
     'editor' : editor, 
     'up_votes' : up_votes, 
     'dwon_votes' : down_votes, 
     'total_votes' : total_votes, 
     'links_to' : links_to, 
     'tags' : tags 
    }; 

    return fromObject; 
    //I use the code below as a temporary solution 
    //JSON.encode(fromObject, toEncodable: (date)=>date.toString()); 
    } 
} 

我有一個臨時的解決方案,但我真的希望能夠做到以下幾點。

JSON.encode(posts, toEncodable: (date)=>date.toString()) 

其中posts是Post對象的列表。我期望這將轉換爲Post類的json表示的json列表。我得到的是一串"Instance of 'Post'"字符串。 所以問題是,這個語法不再被支持,還是我應該做一些不同的事情?

回答

1

看來你只能用toEncodable:這個toJson()後備。

如果您的包裹中的日期提供toJson()你不需要使用toEncodable:類:

class JsonDateTime { 
    final DateTime value; 
    JsonDateTime(this.value); 

    String toJson() => value != null ? value.toIso8601String() : null; 
} 

class Post { 
    ... 
    Map toJson() => { 
    'post_id' : post_id, 
    'title' : title, 
    'description' : description, 
    'posted_at' : new JsonDateTime(posted_at), 
    'last_edited' : new JsonDateTime(last_edited), 
    'user' : user, 
    'editor' : editor, 
    'up_votes' : up_votes, 
    'dwon_votes' : down_votes, 
    'total_votes' : total_votes, 
    'links_to' : links_to, 
    'tags' : tags 
    }; 
} 

或可替換地確保toEncodeable:處理每一個不支持類型:

print(JSON.encode(data, toEncodable: (value) { 
    if (value is DateTime) { 
    return value.toIso8601String(); 
    } else { 
    return value.toJson(); 
    } 
})); 
+0

我誤解了文檔。我爭取'toEncodable'運行在由toJson()返回的不可編碼對象的子元素上。我最終通過稍微改變Map來解決它:''posted_at':posted_at.toI8601String(),'last_edited':last_edited.toIso8601String(),'並且完全移除了'toEncodable'。 – Lukasz

+0

這將是很好,但似乎並非如此。當然這也是一個很好的解決方案。 –

+1

'toEncodable'函數是要使用的函數,沒有其他不可編碼對象的回退。如果你沒有提供另一個'toJson'函數,那麼它只是默認的'toEncodable'函數。 – lrn