【发布时间】:2015-04-27 13:25:25
【问题描述】:
我在我的 asp.net mvc 项目中使用 azure cache 作为缓存提供程序和 c# 我使用这种方法通过 JsonSerializerSettings 序列化我的数据
public static JsonSerializerSettings GetDefaultSettings()
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
Binder = new TypeManagerSerializationBinder(),
ContractResolver = new PrivateSetterContractResolver()
};
settings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.RoundtripKind });
return settings;
}
我的对象是这样的
{
"Name": "Bad Boys III",
"Description": "It's no Bad Boys",
"Classification": null,
"Studio": null,
"ReleaseCountries": null
}
一切正常,但我想为空列返回“{}”而不是 null。
{
"Name": "Bad Boys III",
"Description": "It's no Bad Boys",
"Classification": {},
"Studio": {},
"ReleaseCountries": {}
}
有什么配置可以帮我做吗?
【问题讨论】:
-
string Json = jsonstring.Replace("null", "{}");
-
我正在使用这个方法来反序列化________ public object Deserialize(Stream stream) { JsonSerializer serializer = JsonSerializer.Create(this.Settings); JsonReader reader = new JsonTextReader(new StreamReader(stream, Encoding.UTF8));返回序列化程序。反序列化(阅读器); }
-
不确定,但您可以尝试使用此 [DefaultValue("")] public string FollowUpEmailAddress { get;放; } 在你的模型上,而不是空文本,一个空的 jsononject
-
@Amir:我原来的答案可能是错误的并且不会起作用,所以我更新了它。调整您的自定义 ContractResolver 应该是适合您的方式,请参阅我的更新答案...
标签: c# json asp.net-mvc serialization