This question already has an answer here:
I'm using Newtonsoft Json serialization (with Web API 2).
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?
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.
Here is what the converter might look like:
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);
}
}
To use it, mark your JSON property with a [JsonConverter]
attribute like this:
class Foo
{
...
[JsonConverter(typeof(RawJsonConverter))]
public string YourJsonProperty { get; set; }
...
}
Here is a demo: https://dotnetfiddle.net/BsTLO8
You can encode the embedded JSON string. Base64 should do nicely.
How to encode JSON embedded within JSON
On the browser side, Javascript btoa()
may do, but see this thread:
How can you encode a string to Base64 in JavaScript?
On server side (C#) you probably want to start with System.Convert
methods like Convert.FromBase64String(s)
https://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx
Another useful question:
来源:https://stackoverflow.com/questions/32293271/newtonsoft-json-serialize-a-class-where-one-of-the-properties-is-json