Unity使用Get和Post传递json数据并转换成class对象
此文写的并不是使用UnityRequest等等Unity自带的方法。
1、Get方法
public static async Task<string> DoGet(string requestUrl, string parms) { string reslut = ""; string uri = ""; // url + "?" + parms; if (string.IsNullOrEmpty(parms)) { uri = requestUrl; } else { uri = requestUrl + "?" + parms; } string responseBody = string.Empty; using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("Method", "Get"); httpClient.DefaultRequestHeaders.Add("KeepAlive", "false"); httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); HttpResponseMessage response = await httpClient.GetAsync(uri); response.EnsureSuccessStatusCode(); responseBody = await response.Content.ReadAsStringAsync(); } return responseBody; }
调用:
string u2 = "http://" + ip + "/api/WeatherForecast/GetGameList"; string data2 = await HttpHelper.DoGet(u2, "");
类名 info = JsonConvert.DeserializeObject<类名>(data2);
2、Post
public static async Task<string> DoPost(string Url, object message) { try { //var res = new T(); string jsonContent = message == null ? "" : JsonConvert.SerializeObject(message); string responseBody = string.Empty; using (HttpClient httpClient = new HttpClient()) { var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); httpClient.DefaultRequestHeaders.Add("Method", "Post"); HttpResponseMessage response = await httpClient.PostAsync(Url, content); response.EnsureSuccessStatusCode(); responseBody = await response.Content.ReadAsStringAsync(); //res = (T)JsonConvert.DeserializeObject<T>(responseBody); return responseBody; } } catch (Exception ex) { return ""; } }
调用:
string js = await HttpHelper.DoPost(@"https://****", null); //JObject? result = JsonConvert.DeserializeObject<JObject>(js); 类名 info = JsonConvert.DeserializeObject<类名>(js);
这样写主要是省了回调,省得使用消息者模式消息满天飞。
注意使用await等待时,主线程不会锁死,而使用await时,当前的方法前要加上async,例子如下。
public async void GetPostData() { string js = await HttpHelper.DoPost(@"***********", null); //JObject? result = JsonConvert.DeserializeObject<JObject>(js); PkgInfo info = JsonConvert.DeserializeObject<PkgInfo>(js); }
在把json数据转换成类对象之前,如果需要校验,则使用如下方式:
public async void GetPostData() { string js = await HttpHelper.DoPost(@"***********************", null); JObject result = JsonConvert.DeserializeObject<JObject>(js); string errcode = result["errcode"]?.ToString(); string errmsg = result["errmsg"]?.ToString();
//先验证errcode之后,再根据情况进行类对象的转换。 PkgInfo info = JsonConvert.DeserializeObject<PkgInfo>(js); }
小时候我把老婆种到地下,长大了我能收获一大堆老婆!
我是威少,我是一名Unity游戏的主程,我为自己带盐,希望此文能给您一点点微不足道的帮助,祝你成功!