在远离$type
批注的过程中(为了使数据与语言无关),在理解各种TypeNameHandling
批注和类型协定的优先级时遇到一些问题。
在运输过程中,新类型和旧类型都将包含在同一文件中。因此,该文件必须在除新类型(ISettings
实现)之外的所有类型上都包含类型注释。
我尝试通过以下最小示例重现我的问题:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using Newtonsoft.Json.Serialization;
namespace jsontest
{
// I can't touch this class, even to add annotations
// (in practice there are too many classes to update)
interface IDoNotTouchThis {}
class DoNotTouchThisClass : IDoNotTouchThis {
public IMustHaveType MustHaveType => new HasType();
}
// This is the old data. It must have type annotations to be deserialized.
interface IMustHaveType {}
class HasType : IMustHaveType {}
// This is the new data. It must not have type annotations.
// There is a `JsonConverter` to figure out the types according to the fields.
interface ISettings {}
class SettingsFoo: ISettings {
public String Foo => "NotImportant";
}
class SettingsBar: ISettings {
public String Bar => "NotImportant";
public ISettings SubSettings => new SettingsFoo();
}
// This is the top-level class of the data.
class AllSettings {
public IDoNotTouchThis MustHaveType => new DoNotTouchThisClass();
public ISettings MustNotHaveType => new SettingsFoo();
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.None)] // This helps, but isn't enough
public IReadOnlyList<ISettings> MustNotHaveTypeEither => new List<ISettings> {
new SettingsFoo(),
new SettingsBar(),
};
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Program.Serialize(new AllSettings()));
}
private static JsonSerializerSettings SerializeSettings { get; }
= new JsonSerializerSettings()
{
// For backward compatibility:
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
ContractResolver = new JsonConverterContractResolver(),
};
private static string Serialize<T>(T o)
{
return JsonConvert.SerializeObject(
o,
Formatting.Indented,
Program.SerializeSettings);
}
}
public class JsonConverterContractResolver : DefaultContractResolver
{
/// <inheritdoc />
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
// Here I'm hopping to disable type annotations for all `ISettings` instances.
if (objectType == typeof(ISettings)
|| (objectType.IsClass && objectType.GetInterfaces().Any(i => i == typeof(ISettings)))
|| (objectType == typeof(IReadOnlyList<ISettings>))
|| (objectType == typeof(List<ISettings>)))
{
if (contract is JsonContainerContract objectContract)
{
objectContract.ItemTypeNameHandling = TypeNameHandling.None;
}
}
return contract;
}
}
}
在此示例中,我们得到以下信息:
{
// Not necessary, but doesn't hurt:
"$type": "jsontest.AllSettings, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"MustHaveType": {
"$type": "jsontest.DoNotTouchThisClass, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"MustHaveType": {
"$type": "jsontest.HasType, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
}
},
"MustNotHaveType": {
"$type": "jsontest.SettingsFoo, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"Foo": "NotImportant"
},
"MustNotHaveTypeEither": {
"$type": "System.Collections.Generic.List`1[[jsontest.ISettings, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"$values": [
{
"Foo": "NotImportant"
},
{
"Bar": "NotImportant",
"SubSettings": {
"Foo": "NotImportant"
}
}
]
}
}
代替
{
// Not necessary, but doesn't hurt:
"$type": "jsontest.AllSettings, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"MustHaveType": {
"$type": "jsontest.DoNotTouchThisClass, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"MustHaveType": {
"$type": "jsontest.HasType, pzyc3cmg.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
}
},
"MustNotHaveType": {
"Foo": "NotImportant"
},
"MustNotHaveTypeEither": [
{
"Foo": "NotImportant"
},
{
"Bar": "NotImportant",
"SubSettings": {
"Foo": "NotImportant"
}
}
]
}
我尝试在不同的地方应用TypeNameHandling
/ ItemTypeNameHandling
注释,但没有成功。我正在使用Json.NET寻找格式吗?
答案 0 :(得分:1)
奇怪的是,只有打开它并默认禁用类型序列化,然后在特定的(旧)类型上启用它,我才能使任何东西正常工作。这在您的情况下并不理想,因为这意味着您需要列出解析器中的所有旧类型,我认为这是很多工作。
private static JsonSerializerSettings SerializeSettings { get; }
= new JsonSerializerSettings()
{
// Disable by default
TypeNameHandling = TypeNameHandling.None,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
ContractResolver = new JsonConverterContractResolver(),
};
public class JsonConverterContractResolver : DefaultContractResolver
{
/// <inheritdoc />
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
if (contract is JsonContainerContract objectContract)
{
// enable on old types
if (typeof(IDoNotTouchThis).IsAssignableFrom(objectType))
{
objectContract.ItemTypeNameHandling = TypeNameHandling.All;
}
}
return contract;
}
}
产生的输出就是您所需要的吗?
{
"MustNotHaveType": {
"Foo": "NotImportant"
},
"MustHaveType": {
"MustHaveType": {
"$type": "jsontest.HasType, a0tq5y51.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
}
},
"MustNotHaveTypeEither": [
{
"Foo": "NotImportant"
},
{
"Bar": "NotImportant",
"SubSettings": {
"Foo": "NotImportant"
}
}
]
}
提琴:
答案 1 :(得分:1)
更新:
我能够找到一种方法,可以通过TypeNameHandling
方法在JsonObjectContract
属性上动态设置CreateContract
,这似乎已经解决了问题。查看.Net提琴手here:
public class JsonConverterContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
if (contract is JsonObjectContract)
{
var objectContract = contract as JsonObjectContract;
foreach (var property in objectContract.Properties)
{
var propertyType = property.PropertyType;
if (IsTypeOfISettings(propertyType))
{
// setting type name handling on property level
property.TypeNameHandling = TypeNameHandling.None;
}
}
}
// Here I'm hopping to disable type annotations for all `ISettings` instances.
if (IsTypeOfISettings(objectType))
{
if (contract is JsonContainerContract objectContract)
{
objectContract.ItemTypeNameHandling = TypeNameHandling.None;
}
}
return contract;
}
private bool IsTypeOfISettings(Type objectType)
{
return objectType == typeof(ISettings)
|| (objectType.IsClass && objectType.GetInterfaces().Any(i => i == typeof(ISettings)))
|| (objectType == typeof(IReadOnlyList<ISettings>))
|| (objectType == typeof(List<ISettings>))
|| (objectType == typeof(Dictionary<string, ISettings>));
}
}
原始答案:
我相信是这样,看看这个更新后的.NET fiddle.,我在此提琴中所做的唯一更改是在ItemTypeNameHandling
类属性中将TypeNameHandling
替换为AllSettings
并成功了!通过查看Newtonsoft.Json的内部工作,特别是serializer writer,我得到了启发。
class AllSettings {
public IDoNotTouchThis MustHaveType => new DoNotTouchThisClass();
[JsonProperty(TypeNameHandling = TypeNameHandling.None)]
public ISettings MustNotHaveType => new SettingsFoo();
[JsonProperty(TypeNameHandling = TypeNameHandling.None)]
public IReadOnlyList<ISettings> MustNotHaveTypeEither => new List<ISettings> {
new SettingsFoo(),
new SettingsBar(),
};
}
结果如下:
{
"$type": "jsontest.AllSettings, tciypvk5.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"MustHaveType": {
"$type": "jsontest.DoNotTouchThisClass, tciypvk5.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"MustHaveType": {
"$type": "jsontest.HasType, tciypvk5.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
}
},
"MustNotHaveType": {
"Foo": "NotImportant"
},
"MustNotHaveTypeEither": [
{
"Foo": "NotImportant"
},
{
"Bar": "NotImportant",
"SubSettings": {
"Foo": "NotImportant"
}
}
]
}