c# - 如何在 .NET Core 中使用类对象而不是使用 JObject

我想在这里返回 C# 类对象而不是使用 JObject。有人可以告诉我如何使用它。

private async Task<JObject> GetReceiptById(string Id, string name)
{
    var response = await _ApiService.Get(Id, name);
    var responseStr = await response.Content.ReadAsStringAsync();

    if (response.IsSuccessStatusCode)
    {              
        return JObject.Parse(responseStr);
    }

    throw new Exception(responseStr);
}

这个方法是 return (return JObject.Parse(responseStr));低于 JSON 输出。对于如何创建一个新类。我不知道如何在一个类中全部应用。

{
    "receipts": [
        {
            "ReceiptHeader": {               
                "Company": "DHSC",
                "ErpOrderNum": "730",                
                "DateTimeStamp": "2022-05-14T13:43:57.017"
            },
            "ReceiptDetail": [
                {
                    "Line": 1.0,
                    "ITEM": "PP1016",                    
                    "ITEM_NET_PRICE": 0.0
                },
                {
                    "Line": 2.0,
                    "ITEM": "PP1016",                    
                    "ITEM_NET_PRICE": 0.0
                }
            ],
            "XrefItemsMapping": [],
            "ReceiptContainer": [],
            "ReceiptChildContainer": [],
            "rPrefDO": {
                "Active": null,
                "AllowLocationOverride": null,                
                "DateTimeStamp": null
            }
        }
    ]
}

回答1

您可以使用 ReadAsAsync<T>() 将响应内容绑定到已知类型。 https://docs.microsoft.com/en-us/previous-versions/aspnet/hh835763(v=vs.118)

var result = await response.Content.ReadAsAsync<T>();

在您的示例中,您还将遇到更多问题,因为您在从 Api Service Get 方法获取响应后没有关闭响应。

下面是一个可能的解决方案,您可以将对象类型发送到 Get 方法。 (未测试)

public virtual async Task<T> GetApiCall<T>(Id, name)
        {
            
            //create HttpClient to access the API
            var httpClient = NewHttpClient();
            //clear accept headers
            httpClient.DefaultRequestHeaders.Accept.Clear();
            //add accept json
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //return the client for use

            using (var client = await httpClient )
            {
                //create the response
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    //create return object
                    try
                    {
                        var result = await response.Content.ReadAsAsync<T>();
                        //dispose of the response
                        response.Dispose();
                        return result;
                    }
                    catch
                    {
                       throw;
                    }
                }
               // do something here when the response fails for example
                 var error = await response.Content.ReadAsStringAsync();
                 //dispose of the response
                 response.Dispose();
                 throw new Exception(error);
             }
          }

回答2

您可能正在寻找的是反序列化

你可以用

var model = JsonConvert.Deserialize<YourClass>(responseStr);
return model;

但类 (YourClass) 属性必须与您在 responseStr 中提供的 json 字符串匹配。

作为评论部分,您要求生成类:这是生成类后的样子。

注意:大多数时候,您需要编辑生成的类。

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    public class Receipt
    {
        public ReceiptHeader ReceiptHeader { get; set; }
        public List<ReceiptDetail> ReceiptDetail { get; set; }
        public List<object> XrefItemsMapping { get; set; }
        public List<object> ReceiptContainer { get; set; }
        public List<object> ReceiptChildContainer { get; set; }
        public RPrefDO rPrefDO { get; set; }
    }

    public class ReceiptDetail
    {
        public double Line { get; set; }
        public string ITEM { get; set; }
        public double ITEM_NET_PRICE { get; set; }
    }

    public class ReceiptHeader
    {
        public string Company { get; set; }
        public string ErpOrderNum { get; set; }
        public DateTime DateTimeStamp { get; set; }
    }

    public class Root
    {
        public List<Receipt> receipts { get; set; }
    }

    public class RPrefDO
    {
        public object Active { get; set; }
        public object AllowLocationOverride { get; set; }
        public object DateTimeStamp { get; set; }
    }

生成者:https://json2csharp.com/

相似文章

随机推荐

最新文章