【问题标题】:Deserialize the JSON string using Newtonsoft.JSON使用 Newtonsoft.JSON 反序列化 JSON 字符串
【发布时间】:2015-06-12 06:22:23
【问题描述】:

我想反序列化JSON String

    {\"entityType\":\"Phone\",\"countValue\":30,\"lastUpdateDate\":\"3/25/14 12:00:00 PM MST\",\"RowCnt\":30}.

但我得到了

JSONReaderException "Could not convert string to DateTime: 3/25/14 12:00:00 PM MST".

注意:我们使用Newtonsoft.JSON 进行序列化/反序列化。

【问题讨论】:

标签: json json.net


【解决方案1】:

这实际上比建议的副本稍微复杂一些。 Here's a related question 处理解析包含时区缩写的字符串。

要将答案中的信息与 JSON.NET 一起使用,最好使用自定义转换器:

public class DateTimeWithTimezoneConverter : JsonConverter
{
    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        string t = serializer.Deserialize<string>(reader);

        t = t.Replace("MST", "-07:00");
        // Do other replacements that you need here.

        return 
            DateTime.ParseExact(t, @"M/dd/yy h:mm:ss tt zzz", CultureInfo.CurrentCulture);
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }    


    public override bool CanConvert(Type t)
    {
        return typeof(DateTime).IsAssignableFrom(t);
    }
}

请注意,这只处理您在问题中提出的特定情况。如果您需要更多时区的支持,请查看链接的答案。如果您可以控制生成字符串的代码,则可能需要使用偏移量而不是时区缩写。

以下是您如何使用它的示例:

public class MyType
{
    public string EntityType { get; set; }
    public int CountValue { get; set; }
    public DateTime LastUpdateDate { get; set; }
    public int RowCnt { get; set; }
}

 string json = "{\"entityType\":\"Phone\",\"countValue\":30,\"lastUpdateDate\":\"3/25/14 12:00:00 PM MST\",\"RowCnt\":30}";

 MyType obj = JsonConvert.DeserializeObject<MyType>(
    json,
    new DateTimeWithTimezoneConverter());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 2013-01-18
    相关资源
    最近更新 更多