[英]Serialize and deserialize datetime with newtonsoft
I have a class which contains the ocject DateTime
. 我有一个包含ocject
DateTime
。
public class Refuel
{
public DateTime DateTime { get; set; }
public string Litre { get; set; }
}
When deserializing my text file I get an error. 反序列化我的文本文件时,出现错误。
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.
I tried already with Json settings but it didnt helped. 我已经尝试过使用Json设置,但没有帮助。
JsonSerializerSettings settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat};
this is the json string: 这是json字符串:
"{\"DateTime\":\"2019-02-28T16:21:06.36845+01:00\",\"Litre\":\"23\"}}"
You are trying to deserialize a json string which represents a single object into a list/array of objects which will not work. 您试图将代表单个对象的json字符串反序列化为将不起作用的对象列表/数组。 Either deserialize it into a single object like this:
将其反序列化为单个对象,如下所示:
var obj = JsonConvert.DeserializeObject<Refuel>(json);
Or change your json string to contain a list of objects: 或更改您的json字符串以包含对象列表:
"[{\\"DateTime\\":\\"2019-02-28T16:21:06.36845+01:00\\",\\"Litre\\":\\"23\\"}]"
“ [{\\” DateTime \\“:\\” 2019-02-28T16:21:06.36845 + 01:00 \\“,\\” Litre \\“:\\” 23 \\“}]”
Now you can deserialize it like that: 现在,您可以像这样反序列化它:
var objArray = JsonConvert.DeserializeObject<Refuel[]>(json);
如果要反序列化数组,则需要确保([])的安全。
JsonConvert.DeserializeObject<Refuel[]>(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.