LitJson 不支持 float 类型数据
LitJson默认支持的类型:
public JsonData(bool boolean);
public JsonData(double number);
public JsonData(int number);
public JsonData(long number);
public JsonData(object obj)
public JsonData(string str);
序列化传入float:
错误提示:
LitJson.JsonException: Max allowed object depth reached while trying to export from type System.Single
解决办法:
一 :定义类,float类型使用float或者double代替
如定义数据类:string double 代替原本的float
public class testLitjson
{
public int ioPo;
public string soPo;
public double doPo;
public void InitData(int intPo, string stringPo, double doublePo)
{
ioPo = intPo;
soPo = stringPo;
doPo = doublePo;
}
}
二 :可以扩展相应方法,添加对float等相关类型的支持:
扩展类:
namespace LitJson
{
public class JsonRegister
{
public static int RegFloatType;/** 测试变量 可删除*/
/// <summary>
/// 注册扩展类型,在序列化之前,外部直接调用该方法
/// </summary>
public static void RegisterExtendType()
{
/** 方法二选一即可*/
RegisterFloat();
//RegisterFloat2();
}
/// <summary>
/// Float 扩展方法1 --> float转string
/// </summary>
private static void RegisterFloat()
{
void Exporter(float obj, JsonWriter writer)
{
writer.Write(obj.ToString());
}
JsonMapper.RegisterExporter((ExporterFunc<float>)Exporter);
float Importer(string obj)
{
float fOut;
if (float.TryParse(obj, out fOut))
return fOut;
return 0;
}
JsonMapper.RegisterImporter((ImporterFunc<string, float>)Importer);
RegFloatType = 1;
}
/// <summary>
/// Float 扩展方法2 --> float转double
/// </summary>
private static void RegisterFloat2()
{
void Exporter(float obj, JsonWriter writer)
{
writer.Write(obj);
}
JsonMapper.RegisterExporter((ExporterFunc<float>)Exporter);
float Importer(double obj)
{
return (float)obj;
}
JsonMapper.RegisterImporter((ImporterFunc<double, float>)Importer);
RegFloatType = 2;
}
}
}
示例数据类:
public class testLitjson
{
public int ioPo;
public float foPo;
public double doPo;
public void InitData(int intPo, float floatPo, double doublePo)
{
ioPo = intPo;
foPo = floatPo;
doPo = doublePo;
}
}
使用:外部进行该方法的调用就ok
LitJson.JsonRegister.RegisterExtendType();
测试代码:
LitJson.JsonRegister.RegisterExtendType();
testLitjson json = new testLitjson();
json.InitData(1,15.22354f,15.22354);
string serizCals = LitJson.JsonMapper.ToJson(json);
Debug.LogFormat("{0}{1}","float扩展方法", LitJson.JsonRegister.RegFloatType);
Debug.LogFormat("{0}{1}","序列化数据:",serizCals);
testLitjson uiOp = LitJson.JsonMapper.ToObject<testLitjson>(serizCals);
Debug.LogFormat("uiOp.ioPo:{0} -- uiOp.foPo:{1} -- uiOp.doPo:{2}", uiOp.ioPo, uiOp.foPo, uiOp.doPo);
注意***** 方法一方法二的差异可自行测试( 差异在于float类型)