I'm trying to parse DateTime as Json to MongoDB.
This is my Post Request via Json :
{
"birthdate": "2022-05-19T19:27:44.952Z"
}
This is the part of my C# class:
public DateTime Birthdate { get; set; }
However in the MongoDB it is stored like this:
0001-01-01T00:00:00.000+00:00
But this works:
public DateTime Birthdate { get; set; } = DateTime.Now
however I want to store a custom DateTime
There’s not really enough information here to give a complete answer, but in the console you would need to wrap the string in an ISODate.
{
"birthdate": new ISODate("2022-05-19T19:27:44.952Z")
}
See:
https://www.mongodb.com/docs/manual/reference/method/Date/
Related
I have a list of objects that I de-serialized from a json string that have a start/end time field expressed in UTC time. Eg: "2016-08-22T15:30:00Z" (which is 11:30AM EST). I need to transform the time to a user-friendly format (e.g, "11:30 AM") on the server before sending down the list in JSON for displaying on a web page. Is there a c# function that will help me accomplish this transform the time property to the desired result?
code example:
public class Event
{
public int EventId { get; set; } //1
public string Name { get; set; } //Karate class
public string StartAt { get; set; } //2016-08-22T15:30:00Z
public string EndAt { get; set; } //2016-08-22T16:30:00Z
}
public class Events
{
public List<Event> Events {get; set;}
}
//de-serialize from json string
string eventsForToday = "{}" //some json string from api
var eventList = (Events)JsonConvert.DeserializeObject(eventsForToday, typeof(Events));
foreach (var item in eventList.Events)
{
//needs to be 11:30AM instead of 2016-08-22T15:30:00Z
Console.WriteLine (item.StartAt)
}
I know that the logic is whatever the UTC time is it should be offset by 4 (or 5 depending on time of year). But what is the most straight-forward way to modify the objects? Is there a way to project a new list with the format changed, etc?
You can convert each string into a DateTime. DateTime has a method ToLocalTime() that will do the conversion for you as long as you specify the Kind property of the DateTime. For example,
foreach (var item in eventList.Events)
{
DateTime timeUtc = DateTime.SpecifyKind(DateTime.Parse(item.StartAt), DateTimeKind.Utc);
Console.WriteLine (timeUtc.ToLocalTime()); //Add .ToShortTimeString() if you just want the time (and not the date)
}
However, since your string has a trailing "Z", you should just be able to use Convert.ToDateTime(item.StartAt).ToWhateverString()
This question already has answers here:
Deserializing dates with dd/MM/yyyy format using Json.Net
(9 answers)
Closed 6 years ago.
I have this Json from a web api:
jsonstring ={"users":[{"id":1123,"last_update":"2016-02-28 14:53:04"}],"page":1,"pages":1}
which I want to deserialize in an object like:
public class Rootobject
{
public User[] users { get; set; }
public int page { get; set; }
public int pages { get; set; }
}
public class User
{
public int id { get; set; }
public DateTime last_update { get; set; }
}
for this I use:
var obj= JsonConvert.DeserializeObject<Rootobject>(jsonString);
the result has null for last_update.
jsonstring is a string result from WebClient.DownloadString(url); which look like above example.
How can I get the date on deserialization?
Edit:
None of the solutions from this post Deserializing dates with dd/mm/yyyy format using Json.Net help me fix my issue.
var obj = JsonConvert.DeserializeObject<Rootobject>(jsonString,
new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
Fiddle
Change the property last_update as Nullable, Then it allows you to assign the null literal to the DateTime type. It provides another level of indirection. So use like the following:
public DateTime? last_update { get; set; }
This is for accepting The date even if it is null, you can specify the Date format While Deserializing the JSON. Use this Thread for that
"2016-02-28 14:53:04" is not a valid RFC3339 date time, and I think it can't parse it because of that.
It has to be:
2016-02-28T14:53:04
Also note that the can't be null, since DateTime is a struct. To make it nullable, make the data type DateTime? which does allow null values.
I have one class.
I adding class to mongodb.
but DateTime Properties as shows the string
c#
public class FRM_FORMREQUEST
{
public int ORACLE_ID { get; set; }
public string FORMNUMBER { get; set; }
public string COMPANYCODE { get; set; }
public DateTime? RECORDDATE { get; set; }
public string RECORDUSER { get; set; }
}
mongodb record
{
"_id" : ObjectId("56927dfc249d951f1031f526"),
"ORACLE_ID" : 771653,
"FORMNUMBER" : "4992014309217",
"COMPANYCODE" : "499",
"RECORDDATE" : "2014-08-21T19:35:27",
"RECORDUSER" : "parttime35"
}
Business
var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(FRM_FORMREQUEST);
MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonData);
frmFormCollection.Insert(document);
I want insert like Date
thanks for all help.
The problem is that you're serializing it to JSON using Json.Net, which will write the dates as strings in the ISO 8601 standard format by default. Then you're de-serializing it to a BsonDocument using the BsonSerializer, which (unless you give it any other instructions) will just assume those are strings.
I have to ask, why jump through these hoops? Why not just let the driver serialize your object for you when you call Insert()?
collection.Insert(FRM_FORMREQUEST);
Or, if you have to work with a BsonDocument, use the mongo BsonSerializer to convert your object directly (instead of converting it to Json first).
var document = FRM_FORMREQUEST.ToBson();
collection.Insert(document);
I'm using c# driver to interact with mongoDB.
I have a class that I created and which I populate with the data I get from mongoDB.
One of the properties in that class is DateTime.
The value I get from mongo is /\Date(number)/. Which is ok because this is what I'm suppose to return to the client.
The value that I get from mongo after I retrieve the data is ISODate(some number).
I get an exception: "Invalid JSON primitive: ISODate".
How can I configure mongoDB to save the DateTime like I got it i.e. /\Date(number)/?
Sorry L.B - I didn't noticed your answer but went straight to the answer I was given.
Here's the class I'm trying to deserialize:
public class EventDate
{
public EventDate()
{
}
public int? VenueConfigID { get; set; }
public string Category { get; set; }
public DateTime DateAndTime { get; set; }
public string DisplayDate { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string ShortNote { get; set; }
public string Home { get; set; }
public int? ID { get; set; }
public string Name { get; set; }
}
Here's how I deserialize it:
mongo = MongoServer.Create();
mongo.Connect();
db = mongo.GetDatabase("productionDB");
var col = db.GetCollection<BsonDocument>("eventDates");
var query = Query<PerformerDates>.EQ(ev => ev.PerformerID, performerId);
//MongoCursor<BsonDocument> performer = col.Find(query);
MongoCursor<BsonDocument> performer = col.FindAll();
JavaScriptSerializer js = new JavaScriptSerializer();
List<EventDate> finalMatchedDates = new List<EventDate>();
foreach (var p in performer)
{
//System.Threading.Tasks.Task<EventDate[]> obj2 = JsonConvert.DeserializeObjectAsync<EventDate[]>(p.Elements.ToList()[3].Value.ToString());
EventDate[] obj3 = JsonConvert.DeserializeObject<EventDate[]>(p.Elements.ToList()[3].Value.ToString());
}
mongo.Disconnect();
Solved!!
Eventually I solved it. I used a string instead of a DateTime. When I get it from the DB, I convert it to a DateTime and when I sent it back to the client I serialize it with the format of: /\Date()/
Just use BsonSerializer.Deserialize method.
MongoDB's serializer has a much higher performance over NewtonSoft's Json.Net or Microsoft's DataContractSerializer.
Very common occurring problem! One solution is to use JSON.NET.
See this answer for more help. Although you might be confused with JSON DateTime object but don't worry. It will work!
string json; // Assign JSON here.
var v = Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(json);
Why ServiceStack.Text DeserializeFromString cant convert ISODate formats.
For example, i have json string like
{ "Count" : 4, "Type" : 1, "Date" : ISODate("2013-04-12T00:00:00Z") }
and class
public class TestClass
{
public int Count { get; set; }
public int Type { get; set; }
public DateTime Date { get; set; }
}
and when i try to deserialize from string
JsonSerializer.DeserializeFromString<TestClass>(json);
give me output like
ServiceStack.Text understands ISO8601, too.
You can configure it as the default behaviour with:
JsConfig.DateHandler = JsonDateHandler.ISO8601;
See this answer for more information.
JSON expects the date format like this
"LastRequestTime":"\/Date(928129800000+0530)\/"
So change you date value in Json string and then try. it will deserialized that property properly.