【问题标题】:Access properties of nested JSON object in flutterFlutter中嵌套JSON对象的访问属性
【发布时间】:2020-07-14 05:28:08
【问题描述】:

这是一个颤振/飞镖问题,如果你想问的话。

我有以下 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?

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    当你这样做时

    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 并创建您的 Results:

    List<Result> results = [];
    for (var timestamp in timestamps) {
      final jsonData = parsedJson[timestamp];
      if (jsonData != null) {
        results.add(Result.fromJson(jsonData));
      }
    }
    

    【讨论】:

      【解决方案2】:

      快速回答是使用这个库https://github.com/k-paxian/dart-json-mapper 将您的 json 映射到您的 Dart 类。

      “B*”?这是有目的的,还是错字?无论如何,这是适合您的案例的漂亮代码,没有样板,没有痛苦,没有循环,没有逻辑。还有一个好处,您可以在一行代码中将模型转储回 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
       }
      }
      

      【讨论】:

      • 是的,该对象存储 L* A* B*-Color 值。我不想在json中使用星号,我一定是错过了。
      【解决方案3】:

      在你的结果对象中创建这个函数

          /// 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],
          );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-12
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多