我的课程定义如下
public class HotelRoomResponse
{
public string rateCode { get; set; }
public string rateDescription { get; set; }
public RoomType RoomType { get; set; }
public string supplierType { get; set; }
public int propertyId { get; set; }
public BedTypes BedTypes { get; set; }
public string smokingPreferences { get; set; }
public int rateOccupancyPerRoom { get; set; }
public int quotedOccupancy { get; set; }
public int minGuestAge { get; set; }
public RateInfos RateInfos { get; set; }
public ValueAdds ValueAdds { get; set; }
public string deepLink { get; set; }
public RoomImages RoomImages { get; set; }
}
public class ValueAdd
{
[JsonProperty(PropertyName = "@id")]
public string id { get; set; }
public string description { get; set; }
}
public class ValueAdds
{
private string valueaddsize="0";
[JsonProperty(PropertyName = "size")]
[DefaultValue("0")]
public string size
{
get
{
return !string.IsNullOrEmpty(valueaddsize)
? valueaddsize
: ((DefaultValueAttribute)
(TypeDescriptor.GetProperties(this)["size"].Attributes[
typeof(DefaultValueAttribute)])).Value.ToString();
}
set { valueaddsize = value; }
}
[JsonConverter(typeof(ObjectToArrayConverter<ValueAdd>))]
public List<ValueAdd> ValueAdd { get; set; }
}
public class RoomImage
{
//// private string useurl = "~/no-picture-available.jpg";
// [DefaultValue("~/no-picture-available.jpg")]
// public string url { get; set; }
private string useurl="~/no-picture-available.jpg";
[DefaultValue("~/no-picture-available.jpg")]
public string url
{
get
{
return !string.IsNullOrWhiteSpace(useurl)
? useurl
: ((DefaultValueAttribute)
(TypeDescriptor.GetProperties(this)["url"].Attributes[
typeof(DefaultValueAttribute)])).Value.ToString();
}
set { useurl = value; }
}
}
public class RoomImages
{
public string size { get; set; }
public RoomImage RoomImage { get; set; }
}
在反序列化过程中,缺少一些参数,即每次有几家酒店会生成RoomImages
和ValueAdds
,而有些酒店则不会。{/ p>
我的问题不是在反序列化过程后发送Null,而是尝试设置默认值,但反序列化后不会反映这些值。如何将默认值设置为RoomImages
值为“无图像网址”,将ValueAdds
设置为“无值添加”?
答案 0 :(得分:0)
Json.Net将忽略json中不存在的属性,但我想你会谈论案例2(下面)。然后使用NullValueHandling
枚举即可。
//Case 1 (Json doesn't contain the property)
var image = JsonConvert.DeserializeObject<RoomImage>("{}");
Console.WriteLine(image.Url); //<-- ~/no-picture-available.jpg
//Case 2 (Property is explicitly set to null)
var settings = new JsonSerializerSettings() {NullValueHandling = NullValueHandling.Ignore };
image = JsonConvert.DeserializeObject<RoomImage>("{\"Url\":null}", settings);
Console.WriteLine(image.Url); //<-- ~/no-picture-available.jpg
public class RoomImage
{
string _url = "~/no-picture-available.jpg";
public string Url { get { return _url; } set { _url = value; } }
}