【发布时间】:2017-02-05 09:21:55
【问题描述】:
我在 Unity3D 中使用 Json.NET (v90r1) 的 Net20 库,我正在尝试使用 Json.NET 序列化 Type 类型的字段。
我发现FormatterAssemblyStyle 可以影响自动生成的类型信息,但它似乎不影响Type 类型的字段。例如:
using Newtonsoft.Json;
using System.Runtime.Serialization.Formatters;
using UnityEngine;
public class Example : MonoBehaviour
{
void Start()
{
var settings = new JsonSerializerSettings() {
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
};
Debug.Log(JsonConvert.SerializeObject(new Foo(), settings));
}
}
public class Foo
{
public System.Type type = typeof(void);
}
这将产生以下 JSON 字符串:
{
"$type": "Foo, Assembly-CSharp",
"type": "System.Void, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
}
如您所见,FormatterAssemblyStyle.Simple 已用于$type,但FormatterAssemblyStyle.Full 已用于type。
这是我想要的输出:
{
"$type": "Foo, Assembly-CSharp",
"type": "System.Void, mscorlib"
}
如何使两种类型的打印方式相同?我一直无法找到答案,因为大多数搜索结果与序列化私有成员或序列化类with 类型信息而不是序列化包含 类型的类有关。
【问题讨论】: