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

雨燕双飞 提交于 2019-11-26 18:35:49

问题


This question already has an answer here:

  • Serialize object to JSON that already contains one JSON property 2 answers

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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/32293271/newtonsoft-json-serialize-a-class-where-one-of-the-properties-is-json

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