gpt4 book ai didi

c# - 使用 Json.NET 禁用特定类型的类型注释

转载 作者:行者123 更新时间:2023-12-03 16:58:50 25 4
gpt4 key购买 nike

在搬离过程中$type注释(为了使数据语言独立),我在理解各种 TypeNameHandling 的优先级时遇到了一些问题。注释和类型契约(Contract)。
在转换过程中,新类型和旧类型都将包含在相同的文件中。因此,该文件必须包含除新类型( 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;
}
}
}
( .NET Fiddle link )
通过这个例子,我们得到以下信息:
{
// 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?

最佳答案

奇怪的是,如果我打开它的头部并默认禁用类型序列化,然后在特定(旧)类型上启用它,我只能让任何东西工作。这在您的情况下并不理想,因为这意味着您需要在解析器中列出所有旧类型,我想这需要大量工作。

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"
}
}
]
}
fiddle :
https://dotnetfiddle.net/ckDb6Z

关于c# - 使用 Json.NET 禁用特定类型的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64172481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com