NewtonSoft Json DeserializeObject空Guid字段

时间:2014-02-20 12:46:57

标签: c# asp.net-mvc json knockout.js

我正在使用带有HTML CSS jQuery KnockoutJs前端的ASP.NET MVC C#。

我的HTML页面上有一个模态联系表单。我的想法是,如果我创建一个新的联系人,模态表单会弹出空白值,包括一个空白的隐藏ID字段。

如果我编辑了一个联系人,那么会弹出模态表单,其中填写的字段包括隐藏的id字段。

在我的控制器中,我打算这样做:

public JsonResult Contact(string values)
{
    var contact = JsonConvert.DeserializeObject<contact>(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解决这个问题的,我在自定义JsonConverter 看了here它似乎沿着正确的线路,但是我不知道在哪里跟着这个。

2 个答案:

答案 0 :(得分:6)

自定义转换器看起来像这样,但我觉得这对于一些如此微不足道的东西来说有点矫枉过正。

/// <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": "..."
}

答案 1 :(得分:0)

我遇到了一个问题,即Guid.Empty(00000000-0000-0000-0000-000000000000)值被反序列化为Null向导,从而导致错误。当我将JsonSerializerSettings.DefaultValueHandling值设置为DefaultValueHandling.IgnoreAndPopulate时,反序列化时Guid属性被设置为默认值

var serializedObject = JsonConvert.DeserializeObject<T>(serializedString, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate });