使用newtonsoft序列化和反序列化日期时间

时间:2019-02-28 15:30:55

标签: c# json.net deserialization

我有一个包含对象DateTime的类。

public class Refuel 
{
    public DateTime DateTime { get; set; }
    public string Litre { get; set; }
}

反序列化文本文件时出现错误。

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[OD_TankApp.Models.Refueling]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'DateTime', line 1, position 12.

我已经尝试过使用Json设置,但没有帮助。

JsonSerializerSettings settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat};

这是json字符串:

"{\"DateTime\":\"2019-02-28T16:21:06.36845+01:00\",\"Litre\":\"23\"}}"

2 个答案:

答案 0 :(得分:3)

您正尝试将代表单个对象的json字符串反序列化为无法使用的对象列表/数组。将其反序列化为单个对象,如下所示:

var obj = JsonConvert.DeserializeObject<Refuel>(json);

或更改您的json字符串以包含对象列表:

  

“ [{\” DateTime \“:\” 2019-02-28T16:21:06.36845 + 01:00 \“,\” Litre \“:\” 23 \“}]”

现在您可以像这样反序列化了:

var objArray = JsonConvert.DeserializeObject<Refuel[]>(json);

答案 1 :(得分:0)

如果要反序列化数组,则需要将其保护为([])

JsonConvert.DeserializeObject<Refuel[]>(json);