Dart FormatException:意外字符(在字符1处)

时间:2019-10-12 19:53:08

标签: flutter dart

当我从http库方法get中解析JSON到对象时,我发现了问题

这是响应正文

{"totalReviews": 0,"averageReviewScore": null,"totalReviewScore": 0,"totalFullScore": 0,"lowestScore": null,"highestScore": null,"reviews": []}
    try {
      final response =
          await http.get(httpConst.DOMAIN + httpConst.MY_HISTORY, headers: {
        'Authorization': '$tokenType $accessToken',
        'Content-Type': 'application/json'
      });
      if (response.statusCode == 200) {
        return MyHistory.fromJson(json.decode(response.body));
      } else {
        print(response.statusCode);
        throw Exception('Failed to get review list');
      }
    } catch (e) {
      final log = Map<String, dynamic>.from(json.decode(e.toString()));
      print('err: ${log.toString()}');
      throw Exception('Failed to get review list');
    }


1 个答案:

答案 0 :(得分:0)

请使用以下类和命令进行解析

    [Authorize]
    public class MyBackgroundClass : BackgroundService
    {
    private readonly IHubContext<BigScreenHub> _hub;
    private readonly List<WorkerInfo> WorkerInfos;
    private readonly HttpContext _httpContext;
    public MyBackgroundClass(IHubContext<BigScreenHub> hub, IOptions<AppSettings> settings, IHttpContextAccessor httpContextAccessor)
    {
            _httpContext = httpContextAccessor.HttpContext;
            _hub = hub;
            WorkerInfos = new WorkerInfoProvider(settings.Value.SomeStaticParam,"Need token here", settings.Value.ServicesUrl).WorkerInfos;
    }
    }

代码段

Payload payload = payloadFromJson(response);

相关的有效载荷类

String response = '{"totalReviews": 0,"averageReviewScore": null,"totalReviewScore": 0,"totalFullScore": 0,"lowestScore": null,"highestScore": null,"reviews": []}';
Payload payload = payloadFromJson(response);
print(payload.totalReviews);

完整代码

// To parse this JSON data, do
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
    int totalReviews;
    dynamic averageReviewScore;
    int totalReviewScore;
    int totalFullScore;
    dynamic lowestScore;
    dynamic highestScore;
    List<dynamic> reviews;

    Payload({
        this.totalReviews,
        this.averageReviewScore,
        this.totalReviewScore,
        this.totalFullScore,
        this.lowestScore,
        this.highestScore,
        this.reviews,
    });

    factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        totalReviews: json["totalReviews"] == null ? null : json["totalReviews"],
        averageReviewScore: json["averageReviewScore"],
        totalReviewScore: json["totalReviewScore"] == null ? null : json["totalReviewScore"],
        totalFullScore: json["totalFullScore"] == null ? null : json["totalFullScore"],
        lowestScore: json["lowestScore"],
        highestScore: json["highestScore"],
        reviews: json["reviews"] == null ? null : List<dynamic>.from(json["reviews"].map((x) => x)),
    );

    Map<String, dynamic> toJson() => {
        "totalReviews": totalReviews == null ? null : totalReviews,
        "averageReviewScore": averageReviewScore,
        "totalReviewScore": totalReviewScore == null ? null : totalReviewScore,
        "totalFullScore": totalFullScore == null ? null : totalFullScore,
        "lowestScore": lowestScore,
        "highestScore": highestScore,
        "reviews": reviews == null ? null : List<dynamic>.from(reviews.map((x) => x)),
    };
}

您可以看到打印正确的数据

enter image description here

相关问题