如何告诉JsonConvert.SerializeObject将字符串对象视为JSON

时间:2013-02-27 10:11:17

标签: c# json

如何告诉JsonConvert.SerializeObjectUserPreferences视为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;
  }

1 个答案:

答案 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;
    }
}