[英]Access properties of nested JSON object in flutter
这是一个颤振/飞镖问题,以防万一你想问。
我有以下 JSONObject:
{
"header": [
2223,
2224
],
"2223": {
"L": 3,
"A": 6,
"B": 5,
"Mode": 15,
},
"2224": {
"L": 9,
"A": 6,
"B": 1,
"Mode": 16,
}
}
首先,我从标题对象加载“目录”。
var tagsJson = jsonDecode(jsonContent)['header'];
List<String> timestamps = tagsJson != null ? List.from(tagsJson) : null;
这是我的结果对象,我想将值分配给
class Result {
double L;
double A;
double B;
int mode;
Result({this.L, this.A, this.B, this.mode});
void dump()
{
print(this.L);
print(this.A);
print(this.B);
print(this.mode);
}
}
如何获取时间戳 JSONObjects 的这些值,并使用 flutter 为它们分配相应的结果对象?
快速回答是使用此库https://github.com/k-paxian/dart-json-mapper将您的 json 映射到您的 Dart 类。
“乙*”? 这是出于某种目的还是错别字? 无论如何,这里是您案例的漂亮代码,没有样板,没有痛苦,没有循环,没有逻辑。 还有一个好处是,您可以在一行代码中将模型转储回 json 字符串。
// Here is the result model classes
@jsonSerializable
class ResultItem {
num L;
num A;
num B;
int Mode;
}
@jsonSerializable
class Result {
List<num> header = [];
final Map<String, dynamic> _itemsMap = {};
@jsonProperty
void setItem(String name, dynamic value) {
_itemsMap[name] = JsonMapper.fromMap<ResultItem>(value);
}
@jsonProperty
Map<String, dynamic> getItemsMap() {
return _itemsMap;
}
}
// here is the input json
final json = '''
{
"header": [2223, 2224],
"2223": {
"L": 3,
"A": 6,
"B": 5,
"Mode": 15
},
"2224": {
"L": 9,
"A": 6,
"B": 1,
"Mode": 16
}
}
''';
// Now you have an result model instance populated from json in one line of code
final resultInstance = JsonMapper.deserialize<Result>(json);
// Now you have a result model instance back to json in one line of code
print(JsonMapper.serialize(resultInstance));
控制台输出将是
{
"header": [
2223,
2224
],
"2223": {
"L": 3,
"A": 6,
"B": 5,
"Mode": 15
},
"2224": {
"L": 9,
"A": 6,
"B": 1,
"Mode": 16
}
}
在您的结果对象中创建此函数
/// Creates a [Result] model
/// from a valid JSON Object
///
factory Result.fromJson(Map<String, dynamic> json) => Result(
L: json['L'],
M: json['M'],
B: json['B'],
mode: json['Mode],
);
当你做
var tagsJson = jsonDecode(jsonContent)['header'];
您正在将其余的 JSON 值转储到窗口外。 相反,缓存解析的 JSON 并单独引用它:
final parsedJson = jsonDecode(jsonContent);
final tags = parsedJson['header'];
List<String> timestamps = tags != null ? List.from(tags) : null;
如果您为Result
创建一个fromJson
工厂构造函数,它也会更容易和更清晰:
class Result {
...
factory Result.fromJson(Map<String, dynamic> jsonData) {
double l = (jsonData['L'] ?? 0.0) as double;
double a = (jsonData['A'] ?? 0.0) as double;
double b = (jsonData['B'] ?? 0.0) as double;
int mode = (jsonData['Mode'] ?? 0) as int;
return Result(L: l, A: a, B: b, mode: mode);
}
...
}
现在您可以遍历timestamps
并创建您的Result
:
List<Result> results = [];
for (var timestamp in timestamps) {
final jsonData = parsedJson[timestamp];
if (jsonData != null) {
results.add(Result.fromJson(jsonData));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.