IndieGame/client/Assets/Ether/Scripts/Tools/Json/JsonTools.cs

77 lines
2.0 KiB
C#
Raw Normal View History

2024-10-11 10:12:15 +08:00
/********************************************************************
: JsonTools.cs
:
: 1982614048@qq.com
: 2024/03/29 17:28:19
:
: 2024/04/03 15:59:41
: Json工具类
*********************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
//using LitJson;
using System.ComponentModel;
using System;
using Newtonsoft.Json.Linq;
public static class JsonTools
{
/// <summary>
/// 对象转Json
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJson(object obj, bool isFormat = false)
{
return JsonConvert.SerializeObject(obj, isFormat ? Formatting.Indented : Formatting.None);
//Debug.Log("当前对象转换的json:" + JsonMapper.ToJson(obj));
//return JsonMapper.ToJson(obj);
}
/// <summary>
/// Json转对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T FromJson<T>(string json)
{
return (T)JsonConvert.DeserializeObject<T>(json);
//try
//{
// Debug.Log("当前的json转对象:" + json);
// T t = JsonMapper.ToObject<T>(json);
// if (!(t is ISupportInitialize iSupportInitialize))
// {
// return t;
// }
// iSupportInitialize.EndInit();
// return t;
//}
//catch
//{
// Debug.LogError("Json反序列化出错");
// return default;
//}
}
public static object FromJson(Type type, string json)
{
return JsonConvert.DeserializeObject(json, type);
}
/// <summary>
/// 克隆对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static T Clone<T>(T t)
{
return FromJson<T>(ToJson(t));
}
}