如何从 json 响应中提取一个级别并将其单独显示为独立数据 - C# .net core

How to extract one level from json response and display it separatedly as independent data - C# .net core

我正在使用 .net core app,没有前端,所以所有代码都在服务器上。

这是HttpClient调用后服务器的响应:

 {
        "productId": null,
        "email": "demo@gmail.com",
        "position": null,
        "title": "demo@gmail.com",
        "price": null,
        "product_metadata": 
        {
            "organization": 
            {
                "organizationId": "",
                "title": null
            },
            "sale_stores": 
            [
                {
                    "storeId": "1",
                    "title": null
                },
                {
                    "storeId": "2",
                    "title": null
                }
            ],
        }
    },

我正在调用外部 API 来获取数据,因此我无法影响调用外部服务器后得到的响应。但是我当然可以在我的服务器上修改这个响应。

我想摆脱 "product_metadata" 级别,这样我就可以为客户创建响应 (稍后将加入)可能如下所示:

  {
        "productId": null,
        "email": "demo@gmail.com",
        "position": null,
        "title": "demo@gmail.com",
        "price": null,
        "organization": 
        {
           "organizationId": "",
           "title": null
        },
        "sale_stores": 
        [
            {
                "storeId": "1",
                "title": null
            },
            {
                "storeId": "2",
                "title": null
            }
         ],
    },

这是我的代码 - 请阅读评论:

public async Task<IEnumerable<ProductDto>> GetProducts(CancellationToken cancellationToken)
{

    var response = await _Client.Get<List<ProductDto>>(url, accessToken, cancellationToken);
    // Somewhere in this Get method call I'm deserializing data to my Dto 
    // return JsonConvert.DeserializeObject<T>(result); < - this happening in Get method

    // Here I need to modify this response to rid of that one level that I dont need 
    // Maybe I can loop results and move it to another Dto without `product_metadata` level but that's performance issue?
    
    return response;
}

这是我的 ProductDto

public class ProductDto
{
    public string ProductId { get; set; }
    public string Email { get; set; }
    public string Position { get; set; }
    public string Title { get; set; }
    public string Price { get; set; }

    [JsonProperty("product_metadata")]
    public ProductMetadataDto ProductMetadata { get; set; }
}

谢谢大家

干杯

将它映射到另一个 DTO 不会有任何性能问题,去吧! :) 从您的 API 映射到您自己控制的模型和 return 是一种最佳实践。 做这样的事情:

public async Task<IEnumerable<MyProductDto>> GetProducts(CancellationToken cancellationToken)
{
    var response = await _Client.Get<List<ProductDto>>(url, accessToken, cancellationToken);
    var mappedResponse = myMapper.Map(response);
    return mappedResponse;
}

如果你有一堆产品,比如 10000 或更多,你真的应该考虑分页:)