在 json flutter 中获取对象

Get object in json flutter

我有这个 JSON 输出(使用 Chopper 库)

{"status":"success","error_message":[],"abc":[{"id":"124"},{"id":"125"}]}

如何获取对象 abc 中的 ID?

Response response = await _repo.submitData(title, description);

var abcResponse = ABCResponse.fromJson(response.body);
    if (abcResponse.status == 'success') {
       // I want print the latest id
  }
}

ABC 响应

part 'abc_response.g.dart';

    @JsonSerializable()
    class ABCResponse extends BaseResponse {
      var abc = new List<ABC>();
      ABCResponse();

      factory ABCResponse.fromJson(Map<String, dynamic> json) =>
          _$ABCResponse(json);
      Map<String, dynamic> toJason() => _$WABCResponseToJson(this);
    }

ABC

 @JsonSerializable()
class ABC {

  ABC();
  var id;
}

编辑

 Response response = await _repository.submitData(title, description);

    var abcResponse = ABCResponse.fromJson(response.body);
    if (abcResponse.status == 'success') {
      var user = json.decode(abcResponse.abc.toString());
      print(user);   // it printing null value
    }

这是解码给定 json 并提取 ID 的示例代码。

import 'dart:convert';

void main() 
{
  var jsonString = '{"status":"success","error_message":[],"abc":[{"id":"124"},{"id":"125"}]}'; // just store input json to a variable.
  var user = json.decode(jsonString.toString()); // convert input to string if it isn't already
  print(user['abc'][0]['id']); // complex(nested) json parsing; prints 124
}

使用 json.decode() 将 json 字符串转换为映射。

  1. user['abc'] 会给你 [{id: 124}, {id: 125}]
  2. user['abc'][0] 会给你 {id: 124}, {id: 125} 即提取 输入列表的第 0 个元素。
  3. 最后['abc'][0]['id']会给你id:124.