【问题标题】:Get object in json flutter在json颤动中获取对象
【发布时间】:2020-02-29 02:57:41
【问题描述】:

我有这个 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
  }
}

ABCResponse

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
    }

【问题讨论】:

  • @GhostCatsaysReinstateMonica 抱歉,这里有什么不清楚的地方?我想获取最新的id,在if块中是124。

标签: json flutter dart fromjson


【解决方案1】:

这是一个解码给定 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 字符串转换为 Map。

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

【讨论】:

  • 我得到空值。
  • 您这边可能有一些语法错误,因为代码在dartpad.dartlang.org上运行良好
  • 请在var abcResponse = ABCResponse.fromJson(response.body);之后分享print(abcResponse.toString())的回复
  • 请在我之前的评论中分享 print 的输出
  • 打印Instance of 'ABCResponse'
猜你喜欢
  • 2020-11-28
  • 1970-01-01
  • 2020-01-25
  • 2021-09-24
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
相关资源
最近更新 更多