Answer the question
In order to leave comments, you need to log in
How to prevent object deserialization with Json.Net?
I need to get an object from a Json file with the following structure
{
"start" : 1,
"finish": 2,
"template" : 3
}
public sealed class ORequest
{
public ORequest() { }
[JsonProperty("start")]
public long? start { get; set; }
[JsonProperty("finish")]
public long? finish { get; set; }
[JsonProperty("template")]
public int? template { get; set; }
}
ORequest outRequest = JsonConvert.DeserializeObject<ORequest>(message, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
});
{
"sta" : 1,
"fini": 2,
"temp" : 3
}
Answer the question
In order to leave comments, you need to log in
Try Required :
[JsonProperty(PropertyName = "start", Required = Required.Always)]
public long? start { get; set; }
if (!outRequest.start.HasValue && !outRequest.finish.HasValue && !outRequest.template.HasValue)
{
outRequest = null;
}
[JsonConverter(typeof(ORequestConverter))]
public sealed class ORequest
{
[JsonProperty("start")]
public long? start { get; set; }
[JsonProperty("finish")]
public long? finish { get; set; }
[JsonProperty("template")]
public int? template { get; set; }
}
public class ORequestConverter : JsonConverter
{
public override bool CanWrite
{
get
{
return false;
}
}
public override object ReadJson
(
JsonReader reader,
Type objectType,
object existingValue, JsonSerializer serializer
)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
var target = (ORequest)Activator.CreateInstance(objectType);
serializer.Populate(reader, target);
if (!target.start.HasValue && !target.finish.HasValue && !target.template.HasValue)
{
// необходимые поля не найдены или имеют значение null
// возвращаем null
return null;
}
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question