77 lines
2.0 KiB
C#
77 lines
2.0 KiB
C#
/********************************************************************
|
|
文件: 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));
|
|
}
|
|
}
|