本文介绍了我如何告诉JsonConvert.SerializeObject将字符串对象视为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何告诉JsonConvert.SerializeObject
将UserPreferences
视为JSON对象(它以字符串形式存储在db中).
How do I tell JsonConvert.SerializeObject
to treat the UserPreferences
as a JSON-object (it is stored in a db as a string).
public int UserId { get; private set; }
[[JsonProperty something]]
public string UserPreferences { get; private set; }
public CFUser(Int32 userId, string userPreferences) {
UserId = userId;
UserPreferences = userPreferences;
}
推荐答案
解决您的问题的一种方法是对UserPreferences
属性使用自定义的JsonConverter
.为此,您需要使用以下属性装饰属性:
An option to address your issue is to use a custom JsonConverter
for the UserPreferences
property. For that, you'll need to decorate the property with the following attribute:
[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;
}
}
这篇关于我如何告诉JsonConvert.SerializeObject将字符串对象视为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!