Serialize object to JSON that already contains one JSON property

前端 未结 3 705
独厮守ぢ
独厮守ぢ 2020-12-04 02:45

In order to increase performance, I have cached the result of a larger operation as JSON in a table - together with a key column to determine which row(s) to return. So the

相关标签:
3条回答
  • 2020-12-04 03:02

    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

    0 讨论(0)
  • 2020-12-04 03:03

    Based on answer by Alex and comment by Shahin, I improved the converter a bit, and also implemented the reader to work also the other way (parse back from JToken to the string property):

    public sealed class RawDataJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var tokenReader = reader as JTokenReader;
            var data = tokenReader.CurrentToken.ToString(Formatting.None);
            return data;
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteToken(JsonToken.Raw, value);
        }
    }
    
    0 讨论(0)
  • 2020-12-04 03:08

    Assuming you have a structure like this for serializing:

    public class Record
    {
        [JsonProperty("id")]
        public int Id
        {
            get;
            set;
        }
    
        [JsonProperty("json")]
        [JsonConverter(typeof(SpecialJsonConverter))]
        public string Json
        {
            get;
            set;
        }
    }
    

    And you use code like this for serialization:

        var data = new []
        { 
            new Record() { Id=1, Json = "{\"property\":\"data\"}" }, 
            new Record() { Id=2, Json = "{\"property\":\"data2\", \"property2\":[1, 2, 3]}" }
        };
    
        var serialized = JsonConvert.SerializeObject(data);
        Console.WriteLine(serialized);
    

    All you need is to write a proper converter for the Json property. Luckily there is a method WriteToken in the JsonWriter class that could serve our needs:

    public sealed class SpecialJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var reader = new JsonTextReader(new StringReader(value.ToString()));
            writer.WriteToken(reader);
        }
    }
    
    0 讨论(0)
提交回复
热议问题