在 ASP.NET Core Web API 中处理 JSON 数据

作者:微信公众号:【架构师老卢】
10-4 10:12
276

JSON(JavaScript 对象表示法)是一种用于数据交换的轻量级、易于阅读的格式。由于其简单性和与各种平台的兼容性,它是 Web API 最流行的格式。在 ASP.NET Core Web API 中,JSON 广泛用于在客户端和服务器之间传输数据。

本文将介绍在 ASP.NET Core Web API 中处理 JSON 数据的基础知识,重点介绍:

  1. 发送 JSON 响应
  2. 接收 JSON 请求
  3. 序列化和反序列化
  4. 使用 Newtonsoft.Json 和 System.Text.Json 的自定义选项

1. 为 JSON 设置 ASP.NET Core Web API

默认情况下,ASP.NET Core Web API 通过内置库支持 JSON。创建新的 Web API 项目时,它会自动配置 JSON 格式。System.Text.Json

首先,创建一个新的 ASP.NET Core Web API 项目:

dotnet new webapi -n JsonDemo  
cd JsonDemo

此命令将创建一个名为“JsonDemo”的新 API 项目。

2. 发送 JSON 响应

在 ASP.NET Core 中,您只需从操作方法返回对象,即可从 API 终端节点返回 JSON 数据。框架会自动将对象序列化为 JSON 格式。

[HttpGet]  
public IActionResult GetProduct()  
{  
    var product = new  
    {  
        Id = 1,  
        Name = "Laptop",  
        Price = 1200  
    };  
      
    return Ok(product);  
}

在此示例中,调用终端节点将返回以下 JSON 响应:GetProduct

{  
    "id": 1,  
    "name": "Laptop",  
    "price": 1200  
}

.接收 JSON 请求

ASP.NET Core 会自动将传入的 JSON 请求反序列化为方法参数或操作的模型绑定。

请考虑以下示例,其中您在 HTTP POST 请求正文中接受一个对象:Product

[HttpPost]  
public IActionResult CreateProduct([FromBody] Product product)  
{  
    if (product == null)  
    {  
        return BadRequest("Invalid product data.");  
    }  
    // Process the product (e.g., save to database)  
    return Ok(product);  
}

以下是您可以通过 POST 请求发送的 JSON 负载示例:

{  
    "id": 1,  
    "name": "Laptop",  
    "price": 1200  
}

4. ASP.NET Core 中的序列化和反序列化

序列化:

序列化是将对象转换为 JSON 字符串的过程。ASP.NET Core 中的库在返回对象时会自动执行此操作。System.Text.Json

对于手动序列化,您可以使用 :JsonSerializer

var product = new Product { Id = 1, Name = "Laptop", Price = 1200 };  
var jsonString = JsonSerializer.Serialize(product);

这会将对象转换为 JSON 字符串。product

反序列化:

反序列化是将 JSON 字符串转换回对象的过程。

var jsonString = "{\"Id\":1,\"Name\":\"Laptop\",\"Price\":1200}";
var product = JsonSerializer.Deserialize<Product>(jsonString);

这会将 JSON 字符串反序列化为对象。Product

5. 将 Newtonsoft.Json 用于高级场景

虽然是默认设置,但您可能需要更高级的自定义或与使用 .System.Text.JsonNewtonsoft.Json

要使用 ,请先安装该软件包:Newtonsoft.Json

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson

然后,修改 or 以使用 :Startup.csProgram.csNewtonsoft.Json

builder.Services.AddControllers()  
    .AddNewtonsoftJson(options =>  
    {  
        options.SerializerSettings.Formatting = Formatting.Indented;  
    });

使用 Newtonsoft.Json 自定义 JSON:

使用 ,您可以使用属性自定义对象的序列化和反序列化方式:Newtonsoft.Json

  • [JsonProperty]:控制 JSON 属性的名称。
public class Product
{
    [JsonProperty("product_id")]
    public int Id { get; set; }
    
    [JsonProperty("product_name")]
    public string Name { get; set; }
    public decimal Price { get; set; }
}

这将输出具有自定义属性名称的 JSON:

{
  "product_id": 1,
  "product_name": "Laptop",
  "price": 1200
}
  • [JsonIgnore]:防止属性被序列化。
ublic class Product  
{  
    public int Id { get; set; }  
    public string Name { get; set; }  
    [JsonIgnore]  
    public decimal Price { get; set; }  
}

该属性将从 JSON 输出中排除。Price

6. 使用 System.Text.Json 自定义 JSON 选项

System.Text.Json还提供自定义功能,例如控制属性名称、忽略 Null 值或格式化输出。

以下是全局修改 JSON 序列化的方法:

builder.Services.AddControllers().AddJsonOptions(options =>  
{  
    options.JsonSerializerOptions.PropertyNamingPolicy = null; // Use original property names  
    options.JsonSerializerOptions.WriteIndented = true;         // Pretty-print JSON  
    options.JsonSerializerOptions.IgnoreNullValues = true;      // Ignore null values  
});

7. 处理 JSON 数组和集合

您可以在 ASP.NET Core Web API 中轻松返回或接受 JSON 数组和集合。

返回 JSON 数组:

[HttpGet]  
public IActionResult GetProducts()  
{  
    var products = new List<Product>  
    {  
        new Product { Id = 1, Name = "Laptop", Price = 1200 },  
        new Product { Id = 2, Name = "Smartphone", Price = 800 }  
    };  
  
    return Ok(products);  
}

这将返回一个 JSON 数组:

[  
  {  
    "id": 1,  
    "name": "Laptop",  
    "price": 1200  
  },  
  {  
    "id": 2,  
    "name": "Smartphone",  
    "price": 800  
  }  
]

接受 JSON 数组:

[HttpPost]  
public IActionResult CreateProducts([FromBody] List<Product> products)  
{  
    if (products == null || !products.Any())  
    {  
        return BadRequest("No products provided.");  
    }  
  
    // Process the product list  
    return Ok(products);  
}

然后,您可以发布一个 JSON 数组:

[  
  {  
    "id": 1,  
    "name": "Laptop",  
    "price": 1200  
  },  
  {  
    "id": 2,  
    "name": "Smartphone",  
    "price": 800  
  }  
]

ASP.NET Core Web API 内置了对序列化、反序列化和自定义的支持,使 JSON 数据的处理变得简单明了。无论您是使用默认 JSON 还是切换到 Web API 以满足更复杂的需求,在 Web API 中处理 JSON 都是灵活而强大的。

相关留言评论
昵称:
邮箱:
阅读排行