一个自定义转换器看起来像这样,但我觉得这对一些如此微不足道的东西有点矫枉过正。
/// <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”模型,因此使它可为空将会很糟糕。 –