要在C#中調用Java方法并處理JSON數據,你可以使用以下步驟:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@PostMapping("/processJson")
public String processJson(@RequestBody String json) {
// 處理JSON數據的邏輯
return "處理成功";
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
static async Task Main(string[] args)
{
string javaUrl = "http://localhost:8080/processJson"; // 替換為你的Java Web服務URL
string jsonData = "{\"key\":\"value\"}"; // 替換為你要發送的JSON數據
await CallJavaWebService(javaUrl, jsonData);
}
static async Task CallJavaWebService(string url, string jsonData)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.ContentEncoding.Add("application/json; charset=utf-8");
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseData = await response.Content.ReadAsStringAsync();
Console.WriteLine("Java Web服務返回的數據: " + responseData);
}
else
{
Console.WriteLine("請求失敗,狀態碼: " + response.StatusCode);
}
}
}
}
在這個例子中,我們首先創建了一個名為MyController
的Java控制器,并暴露了一個處理JSON數據的API接口。然后,在C#端,我們使用HttpClient
類調用該接口,并發送JSON數據。最后,我們處理Java Web服務返回的響應數據。