Newtonsoft Json serialize a class where one of the properties is JSON [duplicate]

别来无恙 提交于 2019-11-27 16:18:17

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

codenheim

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:

How to decode a string of text from a Base64 to a byte array, and the get the string property of this byte array without data corruption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!