NewtonSoft Json DeserializeObject空Guid字段
我正在使用带有HTML CSS jQuery KnockoutJs前端的ASP.NET MVC C#。
我的HTML页面上有一个模态联系表单。 我的想法是,如果我创建一个新的联系人,模式窗体会弹出空白值,包括一个空白隐藏的id字段。
如果我编辑了一个联系人,那么模式表单会弹出填充的字段,包括隐藏的id字段。
在我的控制器中,我打算这样做:
public JsonResult Contact(string values) { var contact = JsonConvert.DeserializeObject(values); if (contact.Id.Equals(Guid.Empty)) { // create a new contact in the database } else { // update an existing one } }
但是,我收到一条错误消息,指出can't convert "" to type Guid
你是如何解决这个问题的NewtonSoft Json,我看过Custom JsonConverter ,它似乎沿着正确的路线,但是我不知道该去哪里。
一个自定义转换器看起来像这样,但我觉得这对于一些如此微不足道的东西来说有点过分。
/// /// Converts a to and from its representation. /// public class GuidConverter : JsonConverter { /// /// Determines whether this instance can convert the specified object type. /// /// Type of the object. /// Returns true if this instance can convert the specified object type; otherwise false . public override bool CanConvert(Type objectType) { return objectType.IsAssignableFrom(typeof(Guid)); } /// /// Reads the JSON representation of the object. /// /// The to read from. /// Type of the object. /// The existing value of object being read. /// The calling serializer. /// The object value. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { try { return serializer.Deserialize(reader); } catch { return Guid.Empty; } } /// /// Writes the JSON representation of the object. /// /// The to write to. /// The value. /// The calling serializer. 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(values, new GuidConverter());
编辑
我认为你的JSON看起来很像这样:
{ "id": "", "etc": "..." }
如果您可以这样做,问题可能会得到解决:
{ "id": null, "etc": "..." }