How to serialize a raw json field?

前端 未结 2 1540
不知归路
不知归路 2021-01-11 16:28

I have a field in the db that store a json string and I want that when I return it in a json result that will be returned as json raw data and not warped with quotes as str

2条回答
  •  被撕碎了的回忆
    2021-01-11 16:34

    With Json.net you can define your own JsonConverters to apply a specific serialization behavior. You may apply it for a specific type or, if you have a view model, a specific property.

    In your case you want to write the Images-string as a raw-string using JsonWriter.WriteRawValue.

    Ie.

    public class PlainJsonStringConverter : Newtonsoft.Json.JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return reader.Value;
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteRawValue((string)value);
        }
    }
    
    public class MyViewModel
    {
        public string id { get; set; }
        [Newtonsoft.Json.JsonConverter(typeof(PlainJsonStringConverter))]
        public string images { get; set; }
        /* ...  */
    }
    

提交回复
热议问题