I have a String of json and need convert to JObject.
Example:
String result = ""{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Municipio__c","url":"/services/data/v37.0/sobjects/Municipio__c/a0V2C000000gIgzUAE"},"Id":"a0V2C000000gIgzUAE","LastModifiedDate":"2017-08-01T18:12:04.000+0000"}]}";"
var json = JObject.Parse(result);
But in the moment of the convertion, the LastModifiedDate has changed the value to my Time Zone .
Like that:
{{
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Municipio__c",
"url": "/services/data/v37.0/sobjects/Municipio__c/a0V2C000000gIgzUAE"
},
"Id": "a0V2C000000gIgzUAE",
"LastModifiedDate": "2017-08-01T15:12:04-03:00"
}
]
}}
The hour was changed: 18:12:04 (hh:MM:ss) to 15:12:04 (hh:MM:ss).
Is there a way to ignore the Time Zone on the parse ?
You have to use JsonConvert
with the appropriate DateTimeZoneHandling
:
var json = JsonConvert.DeserializeObject
( result
, new JsonSerializerSettings()
{ DateTimeZoneHandling = DateTimeZoneHandling.Utc
}
);
The time instances are the same. 18:12:04+00:00
is the same as 15:12:04-03:00
and 21:12:04+03:00
(the current offset in Greece).
The default behaviour when parsing date values is to generate a local DateTime
value, ie its Kind property will be DatTimeKind.Local`. The other DateTimeKind values are UTC and Unspecified.
That doesn't mean that the value changed . Local
is a relative term though - without knowing the actual offset, it's easy to misinterpret it.
As Patrick Hofman explained, you can specify that UTC is used by setting the DateTimeZoneHandling
setting.
An even better way is to specify that DateTimeOffset
will be used instead of DateTime
by using the DateParseHandling = DateParseHandling.DateTimeOffset
property. This will return preserve the original timezone information :
var settings=new JsonSerializerSettings{
DateParseHandling = DateParseHandling.DateTimeOffset
};
var json = JsonConvert.DeserializeObject( result, settings);
In this case, the value will be a DateTimeOffset with the original time and an offset of 00:00
.
I'm using dynamic
here to reduce casting noise:
var settings=new JsonSerializerSettings{
DateParseHandling = DateParseHandling.DateTimeOffset
};
dynamic json = JsonConvert.DeserializeObject( result, settings);
var value=(DateTimeOffset)(json.records[0].LastModifiedDate.Value);
Console.WriteLine("{0:o}",value);
This will return :
2017-08-01T18:12:04.0000000+00:00
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.