Json与List简单互转示例
小菜鸟
2021-11-19 PM
5668℃
0条
/// <summary>
/// json转 List
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static List<PlayerNode> My_fromJson(string json)
{
List<PlayerNode> list = new List<PlayerNode>();
string[] Json_AllSplit = json.TrimStart('[').TrimEnd(']').Replace("},", "|").Replace("}", "").Replace("{", "").Split('|');
for (int i = 0; i < Json_AllSplit.Length; i++)
{
//Debug.Log(Json_AllSplit[i]);
string[] Json_SonSplit = Json_AllSplit[i].Split(',');
string[] Name = Json_SonSplit[0].Split(':');
string[] Score = Json_SonSplit[1].Split(':');
string[] Rank = Json_SonSplit[2].Split(':');
//Debug.Log(Name[1] + ":" + Score[1] + ":" + Rank[1]);
list.Add(new PlayerNode(UnicodeString(Name[1].Replace("\"", "")), int.Parse(Score[1]), int.Parse(Rank[1])));
}
return list;
}
/// <summary>
/// 数据转Json格式
/// </summary>
/// <param name="JsonListData"></param>
/// <returns></returns>
public static string My_ToJson<T>(List<T> JsonListData)
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < JsonListData.Count; i++)
{
sb.Append("{");
sb.Append(GetProperties_Name(JsonListData[i]));
sb.Append("}");
if (i < JsonListData.Count - 1)
{
sb.Append(",");
}
}
sb.Append("]");
return sb.ToString();
}
/// <summary>
/// 获取属性名和属性值
/// </summary>
/// <param name="JsonListData"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
private static string GetProperties_Name<T>(T JsonListData)
{
string jsonString = string.Empty;//初始化字符串
if (JsonListData == null)
{//判断是否为空
return jsonString;
}
//设置获取的约束
System.Reflection.PropertyInfo[] properties = JsonListData.GetType().
GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
//判断属性值是否为空
if (properties.Length <= 0)
{
return jsonString;
}
for (int i = 0; i < properties.Length; i++)
{
string name = properties[i].Name;
object value = properties[i].GetValue(JsonListData, null);
if (properties[i].PropertyType.IsValueType || properties[i].PropertyType.Name.StartsWith("String"))
{
if (properties[i].PropertyType.Name.StartsWith("String") || properties[i].PropertyType.Name.StartsWith("Char"))
{
jsonString += string.Format($"\"{name}\":\"{StringUnicode(value.ToString())}\"");
}
else
{
jsonString += string.Format($"\"{name}\":{value}");
}
if (i < properties.Length - 1)
{
jsonString += string.Format(",");
}
}
else
{
GetProperties_Name(value);
}
}
return jsonString;
}