gpt4 book ai didi

c# - 自定义转换器覆盖 ContractResolver

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:20 24 4
gpt4 key购买 nike

我正在尝试使用自定义转换器修改对象类型,如 here 所述, 连同 CamelCasePropertyNamesContractResolver .

所以转换器是这样的(这里什么都不做):

class MyJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsSubclassOf(typeof(MyType));
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
t.WriteTo(writer);
}
}

我是这样使用它的:

var jsonSerializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
jsonSerializationSettings.Converters.Add(new MyJsonConverter());
var camelCaseJsonOutput = await JsonConvert.SerializeObjectAsync(myObject, Formatting.None, jsonSerializationSettings);

但序列化输出显示属性以大写字母开头,因此似乎使用我的转换器以某种方式取消了驼峰式契约(Contract)解析器...

最佳答案

当你创建

JToken t = JToken.FromObject(value);

它创建没有格式化的原始 json。所以,你可以用你自己的方式控制它,camel,Pascal,wHaTeVeR。

例如:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var myType = value as MyType;
if (myType != null)
{
writer.WriteStartObject();
writer.WritePropertyName("myProperty");
serializer.Serialize(writer, myType.myProperty); // Using this will allow to serialize inner values with CamelCasePropertyNamesContractResolver
writer.WritePropertyName("Inner");
serializer.Serialize(writer, myType.Inner);
...
writer.WriteEndObject();
}
}

对于使用驼峰命名法和附加属性序列化对象,我将采用这种方式(可能不是最有效的)

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartObject();

writer.WritePropertyName("_custom_Prop_");
writer.WriteValue("Custom Property value");

WriteObjectProperties(writer, value);

writer.WriteEndObject();
}

private static void WriteObjectProperties(JsonWriter writer, object value)
{
var myJsonWriter = new JTokenWriter();
var js = new JsonSerializer();
js.ContractResolver = new CamelCasePropertyNamesContractResolver();
js.Serialize(myJsonWriter, value);
var childTokens = myJsonWriter.Token.Children();
foreach (var childToken in childTokens)
{
childToken.WriteTo(writer);
}
}

关于c# - 自定义转换器覆盖 ContractResolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20063787/

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