gpt4 book ai didi

json - 在flutter中访问嵌套JSON对象的属性

转载 作者:行者123 更新时间:2023-12-03 04:14:29 26 4
gpt4 key购买 nike

如果您要提问,这是一个 flutter / Dart 问题。

我有以下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为它们分配相应的Result Object?

最佳答案

当你做

var tagsJson = jsonDecode(jsonContent)['header'];

您正在将其余的JSON值转储到窗口之外。相反,请缓存已解析的JSON并单独引用它:

final parsedJson = jsonDecode(jsonContent);
final tags = parsedJson['header'];
List<String> timestamps = tags != null ? List.from(tags) : null;

如果您为 fromJson创建 Result工厂构造函数,它也将变得更加容易和干净:

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));
}
}

关于json - 在flutter中访问嵌套JSON对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60988251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com