问题描述
json字符串
{
"success": true,
"challenge_ts": "2016-11-03T17:30:00Z",
"hostname": "mydomain.com"
}
班
internal class reCaptchaResponse
{
internal bool success { get; set; }
internal DateTime challenge_ts { get; set; } // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
internal string hostname { get; set; } // the hostname of the site where the reCAPTCHA was solved
internal string[] error_codes { get; set; } // optional
}
尝试序列化
reCaptchaResponse responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<reCaptchaResponse>(jsonResult);
尝试失败,就像...
attempt fails like...
Newtonsoft.Json.JsonConvert.SerializeObject(responseObject)
返回{}
推荐答案
默认情况下,Json.Net仅序列化/反序列化 public 文件和属性,但是您也可以在不更改访问修饰符的情况下进行操作从内部到公开.
Json.Net, by default, only serializes/deserialzes public fileds and properties, but you can also do it without changing access modifiers from internal to public.
只需使用JsonProperty
属性
internal class reCaptchaResponse
{
[JsonProperty]
internal bool success { get; set; }
[JsonProperty]
internal DateTime challenge_ts { get; set; } // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
[JsonProperty]
internal string hostname { get; set; } // the hostname of the site where the reCAPTCHA was solved
[JsonProperty]
internal string[] error_codes { get; set; } // optional
}
(无需修改原始类),甚至可以使用 ContractResolver 选择要在序列化过程中使用的属性/字段
(Without modifing the original class) You can even use ContractResolver to select which properties/fields should be used in serialization process
编辑
尽管这个答案已经被接受,但是我想发布一个代码,其中原始程序集不能被修改.
Although this answer has already been accepted, I want to post a code where the original assembly can not be modified.
var settings = new JsonSerializerSettings() {
ContractResolver = new AllPropertiesContractResolver()
};
reCaptchaResponse responseObject =
JsonConvert.DeserializeObject<reCaptchaResponse>(jsonResult ,settings);
public class AllPropertiesContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
.Select(x => new Newtonsoft.Json.Serialization.JsonProperty()
{
PropertyName = x.Name,
PropertyType = x.PropertyType,
Readable = true,
ValueProvider = new AllPropertiesValueProvider(x),
Writable = true
})
.ToList();
return props;
}
}
public class AllPropertiesValueProvider : Newtonsoft.Json.Serialization.IValueProvider
{
PropertyInfo _propertyInfo;
public AllPropertiesValueProvider(PropertyInfo p)
{
_propertyInfo = p;
}
public object GetValue(object target)
{
return _propertyInfo.GetValue(target); //Serialization
}
public void SetValue(object target, object value)
{
_propertyInfo.SetValue(target, value, null); //Deserialization
}
}
这篇关于JSON.NET的JsonConvert我在做什么错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!