如何在flutter中访问JSON对象?

问题描述 投票:0回答:1

下面是我的代码,我需要从响应正文访问“code”json对象并显示警报,但我的代码失败并抛出无效响应(仅执行其他部分)。执行无法进入if部分,如何解决? Json响应如下:{ “同步数据”:{ "message": "零售商已同步", “代码”:1 } }

 Future<Either<Failure, Q>> parseResponse<Q, R>(
    http.Response response, ComputeCallback<String, R> callback) async {
  if (response == null) {
    print('response is null ');
    return Left(UnknownError());
  } else {
    log('callback : ${callback.toString()}response.statusCode : ${response.statusCode} | response.body ${response.body}');
    try {
      switch (response.statusCode) {
        case 200:
          {
            final Map<String, dynamic> body = json.decode(response.body);
            print("body= $body");
            if (body.containsKey("code")) {
              BaseResponse baseResponse = BaseResponse.fromJson(body);
              print("baseResponse= $baseResponse");
              if (baseResponse.code != 0) {
                if (baseResponse.refreshTokenExpired) {
                  return Left(SessionExpiry(message: baseResponse.message));
                } else if (baseResponse.userResigned) {
                  return Left(UserResigned(message: baseResponse.message));
                }
                return Left(ServerValidation(message: baseResponse.message));
              } else {
                var result = await compute(callback, response.body);
                return Right(result as Q);
              }
            } else {
              return Left(InvalidResponse());
            }
          }
          break;
        case 401:
          return Left(ForbiddenError());
          break;
        case 403:
          return Left(UnAuthorizedError());
          break;
        case 404:
          return Left(ServerError(
              statusCode: response.statusCode, message: "File not found"));
          break;
        case 500:
          return Left(ServerError(
              statusCode: response.statusCode, message: "Server Failure"));
          break;
        default:
          return Left(UnknownError(
              statusCode: response.statusCode, message: response.body));
      }
    } catch (e) {
      // if (kDebugMode) {
      //   throw e;
      // }
      return Left(UnknownError());
    }
  }
json flutter jsonresponse jsonobjectrequest qjsonobject
1个回答
0
投票

您可以使用 dart:convert 库访问 JSON 对象,该库提供了对 JSON 进行编码和解码的函数。以下是有关如何在 Flutter 中访问 JSON 对象的基本指南:

导入'dart:转换';

String jsonString = '{"name": "John", "age": 30}';地图 jsonMap = jsonDecode(jsonString);

示例:-

import 'dart:convert';

void main() {
  // Example JSON string
  String jsonString = '{"name": "John", "age": 30}';

  // Decode JSON string into a Dart object
  Map<String, dynamic> jsonMap = jsonDecode(jsonString);

  // Access JSON properties
  String name = jsonMap['name'];
  int age = jsonMap['age'];

  // Print the values
  print('Name: $name');
  print('Age: $age');

  // Example with JSON array
  String jsonArrayString = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';

  // Decode JSON array string into a Dart list
  List<dynamic> jsonArray = jsonDecode(jsonArrayString);

  // Access elements of the array
  String firstName = jsonArray[0]['name'];
  int secondAge = jsonArray[1]['age'];

  // Print the values
  print('First person: $firstName, Age: $age');
  print('Second person: ${jsonArray[1]['name']}, Age: $secondAge');
}
© www.soinside.com 2019 - 2024. All rights reserved.