如何告诉JsonConvert.SerializeObject
将UserPreferences
视为JSON对象(它作为字符串存储在数据库中)。
public int UserId { get; private set; }
[[JsonProperty something]]
public string UserPreferences { get; private set; }
public CFUser(Int32 userId, string userPreferences) {
UserId = userId;
UserPreferences = userPreferences;
}
答案 0 :(得分:2)
解决您的问题的一个选项是为JsonConverter
属性使用自定义UserPreferences
。为此,您需要使用以下属性修饰属性:
[JsonConverter(typeof(UserPreferencesConverter))]
public string UserPreferences { get; private set; }
以下是完整的示例:
class Program
{
static void Main(string[] args)
{
var cfUser = new CFUser(1, @"{""test"":""ok""}");
var json = JsonConvert.SerializeObject(cfUser);
var deserialized = JsonConvert
.DeserializeObject(json, typeof(CFUser));
}
}
class UserPreferencesConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(
JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
// you may use the following line instead
//return jObject.ToString().Replace("\r\n", "");
return jObject.ToString()
.Where(c => !"\r\n".Contains(c))
.Aggregate<char, string>("", (s, c) => s + c);
}
public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer)
{
writer.WriteRawValue(value.ToString());
}
}
public class CFUser
{
public int UserId { get; private set; }
[JsonConverter(typeof(UserPreferencesConverter))]
public string UserPreferences { get; private set; }
public CFUser(Int32 userId, string userPreferences)
{
UserId = userId;
UserPreferences = userPreferences;
}
}