public static Dictionary <TKey, TValue> JsonToDictionary <TKey, TValue>(string json) { Dictionary <TKey, TValue> dic = new Dictionary <TKey, TValue>(); if (string.IsNullOrEmpty(json)) { return(dic); } object data = SimpleJsonTool.DeserializeObject(json); Type keyType = typeof(TKey); Type valueType = typeof(TValue); IList <object> iList = data as IList <object>; for (int i = 0; i < iList.Count; i++) { IDictionary <string, object> iDatasDic = iList[i] as IDictionary <string, object>; object key = iDatasDic["Key"]; object value = iDatasDic["Value"]; key = ChangeJsonDataByType(keyType, key); value = ChangeJsonDataByType(valueType, value); //Debug.Log("keyType :" + keyType + " valueType:" + valueType + " key:" + key.GetType() + " value:" + value.GetType()); dic.Add((TKey)key, (TValue)value); } return(dic); }
private static IDictionary <string, object> ParseObject(char[] json, ref int index, ref bool success) { IDictionary <string, object> dictionary = new JsonObject(); SimpleJsonTool.NextToken(json, ref index); bool flag = false; IDictionary <string, object> result; while (!flag) { int num = SimpleJsonTool.LookAhead(json, index); if (num != 0) { if (num == 6) { SimpleJsonTool.NextToken(json, ref index); } else { if (num == 2) { SimpleJsonTool.NextToken(json, ref index); result = dictionary; return(result); } string key = SimpleJsonTool.ParseString(json, ref index, ref success); if (!success) { success = false; result = null; return(result); } num = SimpleJsonTool.NextToken(json, ref index); if (num != 5) { success = false; result = null; return(result); } object value = SimpleJsonTool.ParseValue(json, ref index, ref success); if (!success) { success = false; result = null; return(result); } dictionary[key] = value; } continue; } success = false; result = null; return(result); } result = dictionary; return(result); }
private static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder) { bool flag = true; string text = value as string; if (text != null) { flag = SimpleJsonTool.SerializeString(text, builder); } else { IDictionary <string, object> dictionary = value as IDictionary <string, object>; if (dictionary != null) { flag = SimpleJsonTool.SerializeObject(jsonSerializerStrategy, dictionary.Keys, dictionary.Values, builder); } else { IDictionary <string, string> dictionary2 = value as IDictionary <string, string>; if (dictionary2 != null) { flag = SimpleJsonTool.SerializeObject(jsonSerializerStrategy, dictionary2.Keys, dictionary2.Values, builder); } else { IEnumerable enumerable = value as IEnumerable; if (enumerable != null) { flag = SimpleJsonTool.SerializeArray(jsonSerializerStrategy, enumerable, builder); } else if (SimpleJsonTool.IsNumeric(value)) { flag = SimpleJsonTool.SerializeNumber(value, builder); } else if (value is bool) { builder.Append((!(bool)value) ? "false" : "true"); } else if (value == null) { builder.Append("null"); } else { object value2; flag = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out value2); if (flag) { SimpleJsonTool.SerializeValue(jsonSerializerStrategy, value2, builder); } } } } } return(flag); }
public static string ToJson(object data) { object temp = ChangeObjectToJsonObject(data); if (null == temp) { return(""); } return(SimpleJsonTool.SerializeObject(temp)); }
/// <summary> /// json转换为class或struct /// </summary> /// <param name="json"></param> /// <param name="type">class或struct的type</param> /// <returns></returns> public static object JsonToClassOrStruct(string json, Type type) { if (string.IsNullOrEmpty(json)) { return(null); } object obj = SimpleJsonTool.DeserializeObject(json); return(JsonObjectToClassOrStruct(obj, type)); }
public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy) { StringBuilder stringBuilder = GetStringBuilder(); bool flag = SimpleJsonTool.SerializeValue(jsonSerializerStrategy, json, stringBuilder); string res = (!flag) ? null : stringBuilder.ToString(); RecycleStringBuilder(stringBuilder); return(res); }
public static object DeserializeObject(string json) { object result; if (SimpleJsonTool.TryDeserializeObject(json, out result)) { return(result); } throw new SerializationException("Invalid JSON string£º" + json); }
/// <summary> /// Json转换List<T> /// </summary> /// <param name="json"></param> /// <param name="itemType">T的type</param> /// <returns></returns> public static object JsonToList(string json, Type itemType) { if (string.IsNullOrEmpty(json)) { return(null); } object obj = SimpleJsonTool.DeserializeObject(json); object res = JsonObjectToList(obj, itemType); return(res); }
public static object FromJson(Type type, string json) { try { object jsonObj = SimpleJsonTool.DeserializeObject(json); return(ChangeJsonDataToObjectByType(type, jsonObj)); } catch (Exception e) { Debug.LogError("json:" + json + "\n" + e); } return(null); }
public static bool TryFromJson(out object res, Type type, string json) { try { object jsonObj = SimpleJsonTool.DeserializeObject(json); //Debug.Log("TryFromJson:" + jsonObj); res = ChangeJsonDataToObjectByType(type, jsonObj); } catch (Exception e) { Debug.LogError("json:" + json + "\n" + e); res = null; return(false); } return(true); }
public static bool TryDeserializeObject(string json, out object obj) { bool result = true; if (json != null) { char[] json2 = json.ToCharArray(); int num = 0; obj = SimpleJsonTool.ParseValue(json2, ref num, ref result); } else { obj = null; } return(result); }
public static string ToJson(object data) { try { object temp = ChangeObjectToJsonObject(data); if (null == temp) { return(""); } return(SimpleJsonTool.SerializeObject(temp)); } catch (Exception e) { Debug.LogError(e); } return(null); }
private static JsonArray ParseArray(char[] json, ref int index, ref bool success) { JsonArray jsonArray = new JsonArray(); SimpleJsonTool.NextToken(json, ref index); bool flag = false; JsonArray result; while (!flag) { int num = SimpleJsonTool.LookAhead(json, index); if (num != 0) { if (num == 6) { SimpleJsonTool.NextToken(json, ref index); } else { if (num == 4) { SimpleJsonTool.NextToken(json, ref index); break; } object item = SimpleJsonTool.ParseValue(json, ref index, ref success); if (!success) { result = null; return(result); } jsonArray.Add(item); } continue; } success = false; result = null; return(result); } result = jsonArray; return(result); }
private static object ParseValue(char[] json, ref int index, ref bool success) { object result; switch (SimpleJsonTool.LookAhead(json, index)) { case 1: result = SimpleJsonTool.ParseObject(json, ref index, ref success); return(result); case 3: result = SimpleJsonTool.ParseArray(json, ref index, ref success); return(result); case 7: result = SimpleJsonTool.ParseString(json, ref index, ref success); return(result); case 8: result = SimpleJsonTool.ParseNumber(json, ref index, ref success); return(result); case 9: SimpleJsonTool.NextToken(json, ref index); result = true; return(result); case 10: SimpleJsonTool.NextToken(json, ref index); result = false; return(result); case 11: SimpleJsonTool.NextToken(json, ref index); result = null; return(result); } success = false; result = null; return(result); }
private static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder) { builder.Append("{"); IEnumerator enumerator = keys.GetEnumerator(); IEnumerator enumerator2 = values.GetEnumerator(); bool flag = true; bool result; while (enumerator.MoveNext() && enumerator2.MoveNext()) { object current = enumerator.Current; object current2 = enumerator2.Current; if (!flag) { builder.Append(","); } string text = current as string; if (text != null) { SimpleJsonTool.SerializeString(text, builder); } else if (!SimpleJsonTool.SerializeValue(jsonSerializerStrategy, current2, builder)) { result = false; return(result); } builder.Append(":"); if (SimpleJsonTool.SerializeValue(jsonSerializerStrategy, current2, builder)) { flag = false; continue; } result = false; return(result); } builder.Append("}"); result = true; return(result); }
private static object ParseNumber(char[] json, ref int index, ref bool success) { SimpleJsonTool.EatWhitespace(json, ref index); int lastIndexOfNumber = SimpleJsonTool.GetLastIndexOfNumber(json, index); int length = lastIndexOfNumber - index + 1; string text = new string(json, index, length); object result; if (text.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || text.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) { double num; success = double.TryParse(new string(json, index, length), NumberStyles.Any, CultureInfo.InvariantCulture, out num); result = num; } else { long num2; success = long.TryParse(new string(json, index, length), NumberStyles.Any, CultureInfo.InvariantCulture, out num2); result = num2; } index = lastIndexOfNumber + 1; return(result); }
private static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder) { builder.Append("["); bool flag = true; IEnumerator enumerator = anArray.GetEnumerator(); bool result; try { while (enumerator.MoveNext()) { object current = enumerator.Current; if (!flag) { builder.Append(","); } if (!SimpleJsonTool.SerializeValue(jsonSerializerStrategy, current, builder)) { result = false; return(result); } flag = false; } } finally { IDisposable disposable; if ((disposable = (enumerator as IDisposable)) != null) { disposable.Dispose(); } } builder.Append("]"); result = true; return(result); }
/// <summary> /// json转换为Dictionary<k,v> /// </summary> /// <param name="json"></param> /// <param name="keyType">key的type</param> /// <param name="valueType">value的type</param> /// <returns></returns> public static object JsonToDictionary(string json, Type keyType, Type valueType) { object obj = SimpleJsonTool.DeserializeObject(json); return(JsonObjectToDictionary(obj, keyType, valueType)); }
private static string ParseString(char[] json, ref int index, ref bool success) { StringBuilder stringBuilder = GetStringBuilder(); //new StringBuilder(2000); SimpleJsonTool.EatWhitespace(json, ref index); char c = json[index++]; bool flag = false; string result; while (!flag) { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { flag = true; break; } if (c == '\\') { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { stringBuilder.Append('"'); } else if (c == '\\') { stringBuilder.Append('\\'); } else if (c == '/') { stringBuilder.Append('/'); } else if (c == 'b') { stringBuilder.Append('\b'); } else if (c == 'f') { stringBuilder.Append('\f'); } else if (c == 'n') { stringBuilder.Append('\n'); } else if (c == 'r') { stringBuilder.Append('\r'); } else if (c == 't') { stringBuilder.Append('\t'); } else if (c == 'u') { int num = json.Length - index; if (num >= 4) { uint num2; if (!(success = uint.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out num2))) { result = ""; } else { if (55296u > num2 || num2 > 56319u) { stringBuilder.Append(SimpleJsonTool.ConvertFromUtf32((int)num2)); index += 4; continue; } index += 4; num = json.Length - index; if (num >= 6) { uint num3; if (new string(json, index, 2) == "\\u" && uint.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out num3)) { if (56320u <= num3 && num3 <= 57343u) { stringBuilder.Append((char)num2); stringBuilder.Append((char)num3); index += 6; continue; } } } success = false; result = ""; } return(result); } break; } } else { stringBuilder.Append(c); } } if (!flag) { success = false; result = null; return(result); } result = stringBuilder.ToString(); RecycleStringBuilder(stringBuilder); return(result); }
/// <summary> /// Dictionary<k,v>转换为json /// </summary> /// <param name="data"></param> /// <returns></returns> public static string DictionaryToJson(object data) { object obj = DictionaryToJsonObject(data); return(SimpleJsonTool.SerializeObject(obj)); }
/// <summary> /// class或struct转换为json /// </summary> /// <param name="data"></param> /// <returns></returns> public static string ClassOrStructToJson(object data) { object jsonObject = ClassOrStructToJsonObject(data); return(SimpleJsonTool.SerializeObject(jsonObject)); }
/// <summary> /// Json转换为Array /// </summary> /// <param name="json"></param> /// <param name="itemType">数组的类型T[]的T类型</param> /// <returns></returns> public static object JsonToArray(string json, Type itemType) { object obj = SimpleJsonTool.DeserializeObject(json); return(JsonObjectToArray(obj, itemType)); }
private static int LookAhead(char[] json, int index) { int num = index; return(SimpleJsonTool.NextToken(json, ref num)); }
private static int NextToken(char[] json, ref int index) { SimpleJsonTool.EatWhitespace(json, ref index); int result; if (index != json.Length) { char c = json[index]; index++; switch (c) { case ',': result = 6; return(result); case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': result = 8; return(result); case '.': case '/': IL_69: switch (c) { case '[': result = 3; return(result); case '\\': IL_7E: switch (c) { case '{': result = 1; return(result); case '|': IL_93: if (c != '"') { index--; int num = json.Length - index; if (num >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; result = 10; return(result); } } if (num >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; result = 9; return(result); } } if (num >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; result = 11; return(result); } } result = 0; return(result); } result = 7; return(result); case '}': result = 2; return(result); default: goto IL_93; } case ']': result = 4; return(result); default: goto IL_7E; } case ':': result = 5; return(result); default: goto IL_69; } } result = 0; return(result); }
private static object ChangeJsonDataToObjectByType(Type type, object data) { object value = null; if (data == null) { return(value); } if (IsSupportBaseValueParseJson(type)) { value = SimpleJsonTool.DeserializeObject(data, type); } else if (type.IsArray) { try { value = JsonObjectToArray(data, type.GetElementType()); } catch (Exception e) { Debug.LogError("Array无法转换类型, data:" + data.GetType().FullName + " type.GetElementType(): " + type.GetElementType().FullName); Debug.LogError(e); } } else if (type.IsGenericType) { if (list_Type.Name == type.Name) { value = JsonObjectToList(data, type.GetGenericArguments()[0]); } else if (dictionary_Type.Name == type.Name) { Type[] ts = type.GetGenericArguments(); value = JsonObjectToDictionary(data, ts[0], ts[1]); } else { value = JsonObjectToClassOrStruct(data, type); } } else { if (type.IsClass || type.IsValueType) { value = JsonObjectToClassOrStruct(data, type); } } if (value == null) { throw new Exception("Json Change Error !"); } try { value = ChangeType(value, type); } catch (Exception e) { throw new Exception("无法转换类型, type:" + type.FullName + " valueType: " + value.GetType().FullName + "\n " + e); } //Debug.Log("ChangeJsonDataToObjectByType:" + value); return(value); }
/// <summary> /// Array转换为Json /// </summary> /// <param name="datas"></param> /// <returns></returns> private static string ArrayToJson(object datas) { object temp = ListArrayToJsonObject(datas, false); return(SimpleJsonTool.SerializeObject(temp)); }
public static string SerializeObject(object json) { return(SimpleJsonTool.SerializeObject(json, SimpleJsonTool.CurrentJsonSerializerStrategy)); }
/// <summary> /// List<T>转换为Json /// </summary> /// <param name="datas">List<T></param> /// <returns>json</returns> public static string ListToJson(object datas) { object temp = ListArrayToJsonObject(datas, true); return(SimpleJsonTool.SerializeObject(temp)); }
public override string ToString() { return(SimpleJsonTool.SerializeObject(this)); }
private void Run() { isCallResult = false; errorCallBackCount = 0; maxRequest = 0; RunHttpQuest("https://ip.seeip.org/geoip", (detail, result) => { //{"offset":"8","city":"Chengdu","region":"Sichuan","dma_code":"0","organization":"AS4134 No.31,Jin-rong Street","area_code":"0","timezone":"Asia\/Chongqing","longitude":104.0667,"country_code3":"CHN","ip":"182.138.139.116","continent_code":"AS","country":"China","region_code":"32","country_code":"CN","latitude":30.6667} object temp = SimpleJsonTool.DeserializeObject(result); // Debug.Log("Type:" + temp.GetType()); IDictionary <string, object> dic = temp as IDictionary <string, object>; detail.SetIP(DicGetString(dic, "ip")); detail.city = DicGetString(dic, "city"); detail.country = DicGetString(dic, "country"); detail.country_code = DicGetString(dic, "country_code"); }); RunHttpQuest("http://ip-api.com/json", (detail, result) => { //{"status":"success","country":"China","countryCode":"CN","region":"SC","regionName":"Sichuan","city":"Chengdu","zip":"","lat":30.6667,"lon":104.0667,"timezone":"Asia/Shanghai","isp":"Chinanet","org":"Chinanet SC","as":"AS4134 No.31,Jin-rong Street","query":"182.138.139.116"} object temp = SimpleJsonTool.DeserializeObject(result); // Debug.Log("Type:" + temp.GetType()); IDictionary <string, object> dic = temp as IDictionary <string, object>; if ("success".Equals(DicGetString(dic, "status"))) { detail.SetIP(DicGetString(dic, "query")); detail.city = DicGetString(dic, "city"); detail.country = DicGetString(dic, "country"); detail.country_code = DicGetString(dic, "countryCode"); } else { throw new Exception("http://ip-api.com/json GetHttpResult status not success:" + result); } }); RunHttpQuest("https://ip.nf/me.json", (detail, result) => { //{"ip":{"ip":"182.138.139.116","asn":"AS4134 No.31,Jin-rong Street","netmask":14,"hostname":"","city":"Chengdu","post_code":"","country":"China","country_code":"CN","latitude":30.66670036315918,"longitude":104.06670379638672}} object temp = SimpleJsonTool.DeserializeObject(result); // Debug.Log("Type:" + temp.GetType()); IDictionary <string, object> dic0 = temp as IDictionary <string, object>; IDictionary <string, object> dic = dic0["ip"] as IDictionary <string, object>; detail.SetIP(DicGetString(dic, "ip")); detail.city = DicGetString(dic, "city"); detail.country = DicGetString(dic, "country"); detail.country_code = DicGetString(dic, "country_code"); }); RunHttpQuest("https://api.ip.sb/geoip", (detail, result) => { // { "longitude":104.0667,"city":"Chengdu","timezone":"Asia\/Shanghai","offset":28800,"region":"Sichuan","asn":4134,"organization":"No.31,Jin-rong Street","country":"China","ip":"182.138.139.116","latitude":30.6667,"continent_code":"AS","country_code":"CN","region_code":"SC"} object temp = SimpleJsonTool.DeserializeObject(result); // Debug.Log("Type:" + temp.GetType()); IDictionary <string, object> dic = temp as IDictionary <string, object>; detail.SetIP(DicGetString(dic, "ip")); detail.city = DicGetString(dic, "city"); detail.country = DicGetString(dic, "country"); detail.country_code = DicGetString(dic, "country_code"); }); RunHttpQuest("https://api.db-ip.com/v2/free/self", (detail, result) => { // { "longitude":104.0667,"city":"Chengdu","timezone":"Asia\/Shanghai","offset":28800,"region":"Sichuan","asn":4134,"organization":"No.31,Jin-rong Street","country":"China","ip":"182.138.139.116","latitude":30.6667,"continent_code":"AS","country_code":"CN","region_code":"SC"} object temp = SimpleJsonTool.DeserializeObject(result); // Debug.Log("Type:" + temp.GetType()); IDictionary <string, object> dic = temp as IDictionary <string, object>; detail.SetIP(DicGetString(dic, "ipAddress")); detail.city = DicGetString(dic, "city"); detail.country = DicGetString(dic, "countryName"); detail.country_code = DicGetString(dic, "countryCode"); }); }