一個自定義轉換器看起來像這樣,但我覺得這對一些如此微不足道的東西有點矯枉過正。
/// <summary>
/// Converts a <see cref="Guid"/> to and from its <see cref="System.String"/> representation.
/// </summary>
public class GuidConverter : JsonConverter
{
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>Returns <c>true</c> if this instance can convert the specified object type; otherwise <c>false</c>.</returns>
public override bool CanConvert(Type objectType)
{
return objectType.IsAssignableFrom(typeof(Guid));
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return serializer.Deserialize<Guid>(reader);
}
catch
{
return Guid.Empty;
}
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
用法:
class Contact
{
[JsonConverter(typeof(GuidConverter))]
public Guid Id { get; set; }
}
或者:
var contact = JsonConvert.DeserializeObject<contact>(values, new GuidConverter());
編輯
我相信,你的JSON看起來像這個有很多:
{
"id": "",
"etc": "..."
}
的問題很可能是固定的,如果你能做到這一點,而不是:
{
"id": null,
"etc": "..."
}
您是否嘗試過製作'contact.Id'屬性爲空的?這可能會解決它。 –
我使用數據庫中使用的「Contact」模型,因此使它可爲空將會很糟糕。 –