在C#中将对象列表发送到Web API方法时,如果JSON为空,可能是由于几个原因造成的。以下是一些基础概念、可能的原因、解决方案以及示例代码。
[JsonIgnore]
属性。[JsonProperty]
属性标记需要序列化的属性。using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
public class MyObject
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("age")]
public int Age { get; set; }
}
public class Program
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main()
{
var objects = new List<MyObject>
{
new MyObject { Name = "Alice", Age = 30 },
new MyObject { Name = "Bob", Age = 25 }
};
var json = JsonConvert.SerializeObject(objects);
Console.WriteLine("Serialized JSON: " + json); // 确保JSON不是空的
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://yourapi.com/endpoint", content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success!");
}
else
{
Console.WriteLine("Failed: " + response.ReasonPhrase);
}
}
}
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
[HttpPost]
public IActionResult Post([FromBody] List<MyObject> objects)
{
if (objects == null || objects.Count == 0)
{
return BadRequest("The JSON payload is empty.");
}
// 处理objects...
return Ok("Received objects.");
}
}
确保对象的所有属性都是公共的并且正确标记以便序列化。在发送请求之前,验证序列化的JSON字符串是否正确。在Web API端,确保参数正确绑定并且能够接收请求体中的数据。通过这些步骤,可以解决JSON为空的问题。
领取专属 10元无门槛券
手把手带您无忧上云