I am trying to remove all indentation from my json :
"date": {
"start": "2020-10-23T15:30:00+00:00"
}
I tried with this
var freeContent = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(content));
But I got
"date": {"start": "2020-10-23T13:30:00+00:00"}
As you can see, the date is modified while I am only expecting for a format change.
How can I remove all indentation from json without changing anything else?
2
Answers
You need to use
DateTimeOffset
type to deserilize this json. Or the timezone infomation will be lost.Then Desirilize like
Test result
I can’t reproduce your exact problem, but if I assume you are currently in a GMT+2 time zone, I was able to reproduce a very similar problem in a fiddle here. The problem seems to be that, somewhere in the deserialization/serialization round trip, Json.NET converts the incoming time to your local time zone but later fails to convert it back to universal time consistently.
The simplest way to solve the problem is to disable Json.NET’s automatic
DateTime
recognition entirely by settingDateParseHandling
toDateParseHandling.None
like so:This ensures your DateTime strings will remain unchanged. Demo fiddle #2 here.
That being said, for large JSON files, it will be more efficiently to eliminate the intermediate
JToken
representation and stream directly from aTextReader
to aTextWriter
using the following extension methods:Then if you have some JSON string in memory you can do:
But if your JSON is in some file on disk, stream from a
StreamReader
to aStreamWriter
.Demo fiddle #3 here.