Newtonsoft Json序列化了其中一个属性为JSON的类 [英] Newtonsoft Json serialize a class where one of the properties is JSON
问题描述
我正在使用Newtonsoft Json序列化(通过Web API 2).
I'm using Newtonsoft Json serialization (with Web API 2).
类的公共属性之一是一个保存JSON数据的String.我想序列化我的类,并包括此公共属性,但我不希望序列化程序处理/修改此字符串的内容.
One of the public properties on my class is a String that holds JSON data. I'd like to serialize my class, and include this public property, but I don't want the serializer to process/modify the contents of this string.
有什么办法可以包含此属性,但不会弄乱它的内容?
Is there any way I can include this property, but not mess with its contents?
推荐答案
您可以使JsonConverter
将字符串属性的原始值写入输出,而无需对其进行更改.您有责任确保该字符串具有有效的JSON,否则结果输出也将不是有效的JSON.
You could make a JsonConverter
to write the raw value of the string property to the output without changing it. You take responsibility for ensuring the string has valid JSON or else the resulting output will not be valid JSON either.
以下是转换器的外观:
class RawJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(string));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// write value directly to output; assumes string is already JSON
writer.WriteRawValue((string)value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// convert parsed JSON back to string
return JToken.Load(reader).ToString(Formatting.None);
}
}
要使用它,请使用以下[JsonConverter]
属性标记您的JSON属性:
To use it, mark your JSON property with a [JsonConverter]
attribute like this:
class Foo
{
...
[JsonConverter(typeof(RawJsonConverter))]
public string YourJsonProperty { get; set; }
...
}
这是一个演示: https://dotnetfiddle.net/BsTLO8
这篇关于Newtonsoft Json序列化了其中一个属性为JSON的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!