Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 library polymer.deserialize; | |
| 6 | |
| 7 import 'dart:convert' show JSON; | |
| 8 import 'dart:mirrors' show reflect, TypeMirror; | |
| 9 | |
| 10 final _typeHandlers = () { | |
| 11 // TODO(jmesserly): switch to map and symbol literal form when supported. | |
| 12 var m = new Map(); | |
| 13 m[const Symbol('dart.core.String')] = (x, _) => x; | |
| 14 m[const Symbol('dart.core.Null')] = (x, _) => x; | |
| 15 m[const Symbol('dart.core.DateTime')] = (x, _) { | |
| 16 // TODO(jmesserly): shouldn't need to try-catch here | |
| 17 // See: https://code.google.com/p/dart/issues/detail?id=1878 | |
| 18 try { | |
| 19 return DateTime.parse(x); | |
| 20 } catch (e) { | |
| 21 return new DateTime.now(); | |
|
blois
2013/09/27 21:40:52
not the default value?
Jennifer Messerly
2013/09/30 17:44:37
Yeah, agreed. I filed https://code.google.com/p/da
| |
| 22 } | |
| 23 }; | |
| 24 m[const Symbol('dart.core.bool')] = (x, _) => x != 'false'; | |
| 25 m[const Symbol('dart.core.int')] = | |
| 26 (x, def) => int.parse(x, onError: (_) => def); | |
| 27 m[const Symbol('dart.core.double')] = | |
| 28 (x, def) => double.parse(x, (_) => def); | |
| 29 return m; | |
| 30 }(); | |
| 31 | |
| 32 /** | |
| 33 * Convert representation of [value] based on type of [defaultValue]. | |
| 34 */ | |
| 35 Object deserializeValue(String value, Object defaultValue, TypeMirror type) { | |
| 36 var handler = _typeHandlers[type.qualifiedName]; | |
|
blois
2013/09/27 21:40:52
Is this extensible? What would it take for someone
Jennifer Messerly
2013/09/30 17:44:37
agreed, added to #13666
| |
| 37 if (handler != null) return handler(value, defaultValue); | |
| 38 | |
| 39 try { | |
| 40 // If the string is an object, we can parse is with the JSON library. | |
| 41 // include convenience replace for single-quotes. If the author omits | |
| 42 // quotes altogether, parse will fail. | |
| 43 return JSON.decode(value.replaceAll("'", '"')); | |
| 44 | |
| 45 // TODO(jmesserly): deserialized JSON is not assignable to most objects in | |
| 46 // Dart. We should attempt to convert it appropriately. | |
| 47 } catch(e) { | |
| 48 // The object isn't valid JSON, return the raw value | |
| 49 return value; | |
| 50 } | |
| 51 } | |
| OLD | NEW |