C#与 Java 后台交互通常通过 HTTP 协议进行,标准做法是将 `List<T>` 序列化为 JSON 字符串发送,Java 后端使用 `@RequestBody` 接收并自动反序列化。
- C#端(发送方)
使用 `System.Text.Json` 或 `Newtonsoft.Json` 将 List 序列化为 JSON 字符串,并通过 HttpClient 发送 POST 请求。
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class DataSender
{
public async Task SendListToJavaAsync()
{
var list = new List<Person>
{
new Person { Id = 1, Name = "Alice" },
new Person { Id = 2, Name = "Bob" }
};
// 序列化为 JSON
string jsonContent = JsonSerializer.Serialize(list);
using var httpClient = new HttpClient();
// 设置内容类型为 application/json
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// 发送 POST 请求到 Java 后台接口
var response = await httpClient.PostAsync("http://localhost:8080/api/receive-list", content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("发送成功");
}
}
}
// 定义对应的数据模型
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
- Java 端(接收方)
使用 Spring Boot 框架,通过 `@RestController` 和 `@PostMapping` 接收请求,`@RequestBody` 会自动将 JSON 数组反序列化为 `List<T>`。
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class DataController {
@PostMapping("/receive-list")
public String receiveList(@RequestBody List<Person> personList) {
// 直接操作接收到的 List
for (Person person : personList) {
System.out.println("ID: " + person.getId() + ", Name: " + person.getName());
}
return "Received " + personList.size() + " items";
}
}
// 定义对应的数据模型,需包含 getter/setter
class Person {
private int id;
private String name;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
关键点:
-
C#端必须设置 `Content-Type` 为 `application/json`。
-
Java 端实体类字段名需与 C#端 JSON 键名一致(默认驼峰命名匹配)。
-
若 C#使用 `Newtonsoft.Json`,序列化方法为 `JsonConvert.SerializeObject(list)`。