使用RestSharp反序列化DummyJson数据时遇JsonException问题求助
解决方案
1. 错误核心原因
DummyJson的/products接口返回的JSON并非直接的产品列表,而是包含products数组的顶层对象,示例结构如下:
{ "products": [/* 产品对象数组 */], "total": 100, "skip": 0, "limit": 30 }
直接反序列化成List<ProductViewModel>会因结构不匹配抛出JsonException。
2. 修复步骤
步骤1:创建响应包装类
新增类匹配DummyJson的响应结构:
public class ProductListResponse { public List<ProductViewModel> products { get; set; } public int total { get; set; } public int skip { get; set; } public int limit { get; set; } }
步骤2:修改ProductClient的GetAllProduct方法
将反序列化目标改为包装类,提取产品列表返回:
public async Task<List<ProductViewModel>> GetAllProduct() { var request = new RestRequest(); var response = await _client.GetAsync<ProductListResponse>(request); return response?.products ?? new List<ProductViewModel>(); }
步骤3:验证修复
重新运行接口调用,即可正确解析JSON并返回产品列表。
3. DummyJson POST请求处理示例(以添加产品为例)
步骤1:创建请求模型
public class CreateProductRequest { public string title { get; set; } public int price { get; set; } public string description { get; set; } public string category { get; set; } public string image { get; set; } }
步骤2:在ProductClient中实现POST方法
public async Task<ProductViewModel> CreateProduct(CreateProductRequest requestModel) { var request = new RestRequest("add", Method.Post); request.AddBody(requestModel, ContentType.Json); var response = await _client.PostAsync<ProductViewModel>(request); return response; }
步骤3:在Controller中调用
[HttpPost] public async Task<IActionResult> Create([FromBody] CreateProductRequest request) { var newProduct = await _client.CreateProduct(request); return CreatedAtAction(nameof(GetAll), new { id = newProduct.id }, newProduct); }
内容的提问来源于stack exchange,提问作者Kaan Yılmazer
相关产品推荐
相关产品推荐

