- 我创建了
JsonConverter
的实现 -
CanConvert
总是返回true。 - 在
ReadJson
中,我有时只想使用"默认"行为,就好像CanConvert
返回false,而我的ReadJson
从未被调用。 - 其他各种帖子都建议我做以下一些变化:
existingValue = existingValue ?? serializer
.ContractResolver
.ResolveContract(objectType)
.DefaultCreator();
serializer.Populate(reader, existingValue);
- 但是,这会在
.DefaultCreator()
上抛出NullReferenceException
。 -
existingValue
总是null
- 从序列化器返回的
ContractResolver
是我自己的。它扩展了JSON.NET的内置CamelCasePropertyNamesContractResolver
,只需覆盖方法CreateConstructorParameters
和CreatePropertyFromConstructorParameter
我如何告诉json.net-"开玩笑,我不知道如何创建这个东西,尽一切努力创建它,如果我告诉你我无法创建它"
请注意,我简化了讨论的问题。我希望有人会回答"只有CanCreate
返回false
"实际上,在我可以并且应该创建对象的许多情况下。
从您的问题和评论中,听起来您有某些情况,您希望转换器读取但不编写,而其他情况则是您想要编写但不阅读的情况。您已经通过将功能分为两个转换器,然后让每个转换器的CanConvert
方法在适当时间返回true或false来解决问题。这当然是一种可行的方法,似乎对您有用,这很棒。但是,我想提供另一种解决方案。
除了CanConvert
方法外,基本JsonConverter
还提供两个虚拟布尔属性,您可以覆盖:CanRead
和CanWrite
。(默认情况下均返回True。)这些属性直接控制ReadJson
和WriteJson
是否由序列化器调用特定转换器。因此,例如,如果CanRead
返回false,则不会调用ReadJson
,即使CanConvert
返回true,也将使用默认的读取行为。这使您可以非常整齐地设置一个不对称的转换器。例如,您可能会有一种情况,您希望将疯狂的JSON格式化为更明智的对象结构,但是当您再次序列化时,您不想回到疯狂的JSON格式 - 您只是想要默认序列化。在这种情况下,您将覆盖转换器中的CanWrite
以始终返回false。然后,您可以将WriteJson
的实现留为空白,也可以将其投掷NotImplementedException
;它永远不会被称为。
您的情况听起来比这更复杂,但是您仍然应该能够操纵CanRead
和CanWrite
属性以实现所需的结果。以下是一个人为的示例,它显示了我们如何根据情境变量切换ReadJson
和WriteJson
方法。
public class Program
{
public static void Main(string[] args)
{
string json = @"{""keys"":[""foo"",""fizz""],""values"":[""bar"",""bang""]}";
CustomConverter converter = new CustomConverter();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(converter);
// Here we are reading a JSON object containing two arrays into a dictionary
// (custom read) and then writing out the dictionary JSON (standard write)
Console.WriteLine("--- Situation 1 (custom read, standard write) ---");
converter.Behavior = ConverterBehavior.CustomReadStandardWrite;
json = DeserializeThenSerialize(json, settings);
// Here we are reading a simple JSON object into a dictionary (standard read)
// and then writing out a new JSON object containing arrays (custom write)
Console.WriteLine("--- Situation 2 (standard read, custom write) ---");
converter.Behavior = ConverterBehavior.StandardReadCustomWrite;
json = DeserializeThenSerialize(json, settings);
}
private static string DeserializeThenSerialize(string json, JsonSerializerSettings settings)
{
Console.WriteLine("Deserializing...");
Console.WriteLine(json);
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json, settings);
foreach (var kvp in dict)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
Console.WriteLine("Serializing...");
json = JsonConvert.SerializeObject(dict, settings);
Console.WriteLine(json);
Console.WriteLine();
return json;
}
}
enum ConverterBehavior { CustomReadStandardWrite, StandardReadCustomWrite }
class CustomConverter : JsonConverter
{
public ConverterBehavior Behavior { get; set; }
public override bool CanConvert(Type objectType)
{
return typeof(IDictionary<string, string>).IsAssignableFrom(objectType);
}
public override bool CanRead
{
get { return Behavior == ConverterBehavior.CustomReadStandardWrite; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Console.WriteLine("ReadJson was called");
// Converts a JSON object containing a keys array and a values array
// into a Dictionary<string, string>
JObject jo = JObject.Load(reader);
return jo["keys"].Zip(jo["values"], (k, v) => new JProperty((string)k, v))
.ToDictionary(jp => jp.Name, jp => (string)jp.Value);
}
public override bool CanWrite
{
get { return Behavior == ConverterBehavior.StandardReadCustomWrite; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Console.WriteLine("WriteJson was called");
// Converts a dictionary to a JSON object containing
// a keys array and a values array from the dictionary
var dict = (Dictionary<string, string>)value;
JObject jo = new JObject(new JProperty("keys", new JArray(dict.Keys)),
new JProperty("values", new JArray(dict.Values)));
jo.WriteTo(writer);
}
}
输出:
--- Situation 1 (custom read, standard write) ---
Deserializing...
{"keys":["foo","fizz"],"values":["bar","bang"]}
ReadJson was called
foo: bar
fizz: bang
Serializing...
{"foo":"bar","fizz":"bang"}
--- Situation 2 (standard read, custom write) ---
Deserializing...
{"foo":"bar","fizz":"bang"}
foo: bar
fizz: bang
Serializing...
WriteJson was called
{"keys":["foo","fizz"],"values":["bar","bang"]}
小提琴:https://dotnetfiddle.net/bdtson