将json结果转换为dart模型 [英] converting json result to dart model

查看:118
本文介绍了将json结果转换为dart模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些通用类型在API上使用,这些API返回的数据低于json结果

I am using some generic type to use on API that return data which json result is below

{
  "apiResult": {
    "dataResult": {
      "accessToken": "access_token_string",
      "refreshToken": "refresh_token_string"
    },
    "dataIsSuccess": true,
    "dataError": "Service name : LoginService - No error",
    "dataCustomError": "Service name : LoginService - No custom error",
    "dataReturnCode": 200,
    "dataCount": null
  },
  "apiException": "NO_ERROR_FROM_API",
  "apiCustomException": "Method name : ApplicationUserLoginAsync",
  "apiReturnCode": 200,
  "apiIsSuccess": true
}

dataResult 是我的数据库结果模型,是通用类型(可以是令牌响应模型或产品列表).因此,我需要将此json模型转换为DART类.我已经尝试了一些代码,但是无法按我的意愿做

dataResult is my database result model which is a generic type (it can be a token response model or list of product). So I need to convert this json model to DART class. I have tried some code but could not to do it as I wanted

请需要帮助.

编辑

我尝试了一些在线工具来生成dart类代码,但是我遇到的问题是 dataResult 属性是如下所示的通用属性

I have tried some online tool to generate dart class code but the problem I had is that dataResult property is a generic property as below

public class DataReturn<T>
{
    public T DataResult { get; set; }
    public bool DataIsSuccess { get; set; }
    public string DataError { get; set; }
    public string DataCustomError { get; set; }
    public int DataReturnCode { get; set; }
    public long? DataCount { get; set; }
}

因此,我在上面添加的json对象是对DataReturn类的通用TokenResponseModel的实现.

So the json object that I added above is a implementation of generic TokenResponseModel to DataReturn class.

所以我需要一个解决方案.

So I need a solution to this.

编辑2

添加有关我的问题的一些信息.首先在后端,我使用的是Net Core Web API.

adding some information about my question. first at the backend I am using net core web api.

Web api响应方法(如果结果正确)使用下面的通用 OkObjectResult

web api response method (if result is ok) uses below generic OkObjectResult

   public class BaseControllerReturn<T>
            public OkObjectResult Ok(T t, string methodFullName)
            {
                ApiReturn<T> apiReturn = new ApiReturn<T>
                {
                    ApiResult = t,
                    ApiException = "NO_ERROR_FROM_API",
                    ApiCustomException = $"Method name : {methodFullName}",
                    ApiReturnCode = (int)ApiMessageType.CAM200,
                    ApiIsSuccess = true
                };
    
                return new OkObjectResult(apiReturn);
            }
}

ApiResult 类是

public class ApiReturn<T> : IApiReturn<T>
{
    public T ApiResult { get; set; }
    public string ApiException { get; set; }
    public string ApiCustomException { get; set; }
    public int ApiReturnCode { get; set; }
    public bool ApiIsSuccess { get; set; }
}

Web Api控制器操作方法返回如下

Web Api controller action method return as below

IDataReturn<ICollection<SomeEntity>> dataReturn;
var controllerReturn = new BaseControllerReturn<IDataReturn<ICollection<SomeEntity>>>();
....
....
....
return controllerReturn.Ok(dataReturn, ControllerName + " - " + MethodFullName);

DataReturn 类,您可以在上方看到它.

DataReturn class you can see it above.

因此,Web Api方法在DataReturn泛型类内返回数据库结果,而Api方法在ApiResult内返回DataReturn对象,并且我具有如下的Api Return对象

So Web Api methods return DB result inside the DataReturn generic class and Api methods return DataReturn object inside the ApiResult and I have Api Return object as below

ApiReturn< DataReturn>可以看到如下

ApiReturn<DataReturn> which can be seen as below

{
  "apiResult": {
    "dataResult": {
      "accessToken": "access_token_string",
      "refreshToken": "refresh_token_string"
    },
    "dataIsSuccess": true,
    "dataError": "Service name : LoginService - No error",
    "dataCustomError": "Service name : LoginService - No custom error",
    "dataReturnCode": 200,
    "dataCount": null
  },
  "apiException": "NO_ERROR_FROM_API",
  "apiCustomException": "Method name : ApplicationUserLoginAsync",
  "apiReturnCode": 200,
  "apiIsSuccess": true
}

在此示例中,SomeEntity是

In this example SomeEntity is

public class TokenResponseModel
{
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
}

所以我希望这些信息足以澄清问题.

So I hope these information is enough to clarify the question.

使用相同的ApiResult和DataResult泛型类的Web API的另一个响应.

another response from web api that use same ApiResult and DataResult generic class.

{
    "apiResult": {
        "dataResult": [
            {
                "stockDetailId": "ac9d6aac-3b0e-42f7-ba87-85cf6647cde9",
                "stockDetail": {
                    "stockId": "8802d1e0-b044-4986-9e44-74f68fe2068e",
                    "secondCurrency": 0,
                    "thirdCurrency": 0,
                    "retailVatType": 4,
                    "ecommerce": false,
                    "description": null,
                    "id": "ac9d6aac-3b0e-42f7-ba87-85cf6647cde9",
                    "isActive": true,
                    "createdUser": "ed086e08-fbdf-4974-d566-08d7cb0d5a98",
                    "createdDate": "2020-07-25T14:15:42.0056828",
                    "updatedUser": "ed086e08-fbdf-4974-d566-08d7cb0d5a98",
                    "updatedDate": "2020-07-25T14:15:42.0056828"
                },
                "vendorId": null,
                "vendor": null,
                "manufacturerId": null,
                "manufacturer": null,
                "priceListId": null,
                "priceList": null,
                "discountMatrixId": null,
                "discountMatrix": null,
                "stockEcommerceId": null,
                "stockEcommerce": null,
                "stockOpenCarts": null,
                "stockUnits": null,
                "stockBarcodes": null,
                "stockGroups": null,
                "stockCategories": null,
                "stockFiles": null,
                "accountMatchings": null,
                "code": "334472",
                "name": "YETIS MATIK DAG ESINTISI 2500GR*6",
                "currencyType": 1,
                "vatType": 4,
                "sellingPrice": null,
                "id": "8802d1e0-b044-4986-9e44-74f68fe2068e",
                "isActive": true,
                "createdUser": "ed086e08-fbdf-4974-d566-08d7cb0d5a98",
                "createdDate": "2020-07-25T14:15:42.0056828",
                "updatedUser": "ed086e08-fbdf-4974-d566-08d7cb0d5a98",
                "updatedDate": "2020-07-25T14:15:42.0056828"
            }
        ],
        "dataIsSuccess": true,
        "dataError": "Service name : StockService - No error",
        "dataCustomError": "Service name : StockService - No custom error",
        "dataReturnCode": 200,
        "dataCount": 1
    },
    "apiException": "NO_ERROR_FROM_API",
    "apiCustomException": "Method name : StocksController - ListAsync",
    "apiReturnCode": 200,
    "apiIsSuccess": true
}

推荐答案

您可以使用 quicktype.io 之类的工具来将json转换为dart类.

You can use tool like quicktype.io to convert json to dart class.

// To parse this JSON data, do
//
//     final generalPublicLoginResponse = generalPublicLoginResponseFromJson(jsonString);

import 'dart:convert';

GeneralPublicLoginResponse generalPublicLoginResponseFromJson(String str) => GeneralPublicLoginResponse.fromJson(json.decode(str));

String generalPublicLoginResponseToJson(GeneralPublicLoginResponse data) => json.encode(data.toJson());

class GeneralPublicLoginResponse {
    GeneralPublicLoginResponse({
        this.apiResult,
        this.apiException,
        this.apiCustomException,
        this.apiReturnCode,
        this.apiIsSuccess,
    });

    ApiResult apiResult;
    String apiException;
    String apiCustomException;
    int apiReturnCode;
    bool apiIsSuccess;

    factory GeneralPublicLoginResponse.fromJson(Map<String, dynamic> json) => GeneralPublicLoginResponse(
        apiResult: ApiResult.fromJson(json["apiResult"]),
        apiException: json["apiException"],
        apiCustomException: json["apiCustomException"],
        apiReturnCode: json["apiReturnCode"],
        apiIsSuccess: json["apiIsSuccess"],
    );

    Map<String, dynamic> toJson() => {
        "apiResult": apiResult.toJson(),
        "apiException": apiException,
        "apiCustomException": apiCustomException,
        "apiReturnCode": apiReturnCode,
        "apiIsSuccess": apiIsSuccess,
    };
}

class ApiResult {
    ApiResult({
        this.dataResult,
        this.dataIsSuccess,
        this.dataError,
        this.dataCustomError,
        this.dataReturnCode,
        this.dataCount,
    });

    DataResult dataResult;
    bool dataIsSuccess;
    String dataError;
    String dataCustomError;
    int dataReturnCode;
    dynamic dataCount;

    factory ApiResult.fromJson(Map<String, dynamic> json) => ApiResult(
        dataResult: DataResult.fromJson(json["dataResult"]),
        dataIsSuccess: json["dataIsSuccess"],
        dataError: json["dataError"],
        dataCustomError: json["dataCustomError"],
        dataReturnCode: json["dataReturnCode"],
        dataCount: json["dataCount"],
    );

    Map<String, dynamic> toJson() => {
        "dataResult": dataResult.toJson(),
        "dataIsSuccess": dataIsSuccess,
        "dataError": dataError,
        "dataCustomError": dataCustomError,
        "dataReturnCode": dataReturnCode,
        "dataCount": dataCount,
    };
}

class DataResult {
    DataResult({
        this.accessToken,
        this.refreshToken,
    });

    String accessToken;
    String refreshToken;

    factory DataResult.fromJson(Map<String, dynamic> json) => DataResult(
        accessToken: json["accessToken"],
        refreshToken: json["refreshToken"],
    );

    Map<String, dynamic> toJson() => {
        "accessToken": accessToken,
        "refreshToken": refreshToken,
    };
}



这篇关于将json结果转换为dart模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆