gpt4 book ai didi

json - Newtonsoft JSON序列化器返回空对象

转载 作者:行者123 更新时间:2023-12-04 04:22:31 28 4
gpt4 key购买 nike

好的-我已经将这个问题打了几个小时。是时候寻求帮助了。

我刚刚将Web应用程序项目升级到ASP.NET MVC 4 RC和新的WebApi。
我的Web api方法现在返回EMPTY json“{}”-即使我的对象已完全填充。

我已经用自己的MediaTypeFormatter替换了序列化程序,该介质类型也称为Newtonsoft Json序列化程序,这样我就可以挂接并看到工作正常。
我看到的是一个对象进入序列化器,并以“{}”的形式出现。

在我升级之前,此功能可以正常工作。

这是我的对象

[Serializable]
public class Parameters
{
public string ApplicantName { get; set; }
}

我只是在打电话:
var result = JsonConvert.SerializeObject(new Parameters(){ Name = "test" });

我回来
"{}"

这是怎么回事??

[编辑]

遇到其他问题的人...在浏览完Newtonsoft源代码后,我可以看到我们在最近的更改中遇到了完全相同的问题。

http://json.codeplex.com/discussions/357850

最佳答案

好的-进行了许多更改,结果是对Json输出进行了一些非常根本的更改。这些更改还包括如何应用自定义TypeConverters。

我写了一个基本的解析器(至少对我们来说),使Newtonsoft序列化器的行为更像基本的可序列化对象序列化器-即序列化所有PROPERTIES,并且不使用自定义TypeConverters。

/// <summary>
/// A resolver that will serialize all properties, and ignore custom TypeConverter attributes.
/// </summary>
public class SerializableContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList<Newtonsoft.Json.Serialization.JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);

foreach (var p in properties)
p.Ignored = false;

return properties;
}

protected override Newtonsoft.Json.Serialization.JsonContract CreateContract(Type objectType)
{
var contract = base.CreateContract(objectType);

if (contract is Newtonsoft.Json.Serialization.JsonStringContract)
return CreateObjectContract(objectType);
return contract;
}
}

*注册*
在您的MvcApplication“Application_Start”中...
GlobalConfiguration.Configuration.Formatters
.JsonFormatter.SerializerSettings.ContractResolver =
new SerializableContractResolver()
{
IgnoreSerializableAttribute = true
};

关于json - Newtonsoft JSON序列化器返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11044639/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com