using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using UnityEngine; /// ///整合JSON /// public static class CombineJSON { //public static List jsons = new List(); public static Dictionary jsonsDic = new Dictionary(); /// /// 获取所有设备API /// /// public static string GetCombineJSON() { //创建一个JArray对象,用于存储多个JSON 对象 JArray jsonArray = new JArray(); // 解析JSON字符串,并添加到JArray foreach (var item in jsonsDic.Values) { var jsonObj = JObject.Parse(item); jsonArray.Add(jsonObj); } //创建一个包含JArray的JObject对象 JObject resultObj = new JObject(); resultObj["data"] = jsonArray; //将整合后的JSON输出成字符串 string resultJson = resultObj.ToString(); return resultJson; } /// /// POST修改数据的请求 /// /// /// /// /// public static async Task UpdateJson_POST(string apiUrl, string token, string newData) { var client = new HttpClient(); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(apiUrl), Headers = { { "X-Token", token }, }, Content = new StringContent(newData) { Headers = { ContentType = new MediaTypeHeaderValue("application/json") } } }; using (var response = await client.SendAsync(request)) { response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return body; } } /// /// POST获取数据的请求 /// /// /// /// public static async Task GetJson_POST(string apiUrl, string token) { using (HttpClient httpClient = new HttpClient()) { var client = new HttpClient(); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(apiUrl), Headers = { { "X-Token", token }, }, }; using (var response = await client.SendAsync(request)) { response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); return (body); } } } /// /// 获取GET接口 /// /// /// public static async Task GetJson_GET(string apiUrl) { using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync(apiUrl)) { if (response.IsSuccessStatusCode) { string jsonResult = await response.Content.ReadAsStringAsync(); // 处理返回的JSON数据 Debug.Log(jsonResult); return jsonResult; } else { Debug.Log("请求GET接口失败: " + response.StatusCode); return null; } } } } }