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.
Related
This question already has answers here:
How to deserialize a JObject to .NET object
(3 answers)
Closed 20 days ago.
I have a class like these:
class MyDate
{
int year, month, day;
}
I want to fill an object of this class with the data from this JSON string (only from "dateOfBirth"):
{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}
I know the
JsonConvert.DeserializeObject<>(jsonString)
but I am looking for a way to convert only a single object of a whole JsonString into a .Net object.
I am looking for a DeserializeObject method with a JObject as parameter.
you need to parse your json string, only after this you can deserialize any part you need. Your class should be fixed too.
using Newtonsoft.Json;
MyDate myDate = JObject.Parse(json)["dateOfBirth"].ToObject<MyDate>();
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
class MyDate
{
public int year, month, day;
}
Make sure variable should be public
string str = "{'firstName':'Markoff','lastName':'Chaney','dateOfBirth':{'year':'1901','month':'4','day':'30'}}";
dynamic data = JsonConvert.DeserializeObject(str);
if (data.dateOfBirth != null)
{
string strJson = JsonConvert.SerializeObject(data.dateOfBirth);
MyDate myDate = JsonConvert.DeserializeObject<MyDate>(strJson);
}
You can use SelectToken
var result = JObject.Parse(jsonStr).SelectToken("dateOfBirth").ToObject<MyDate>();
You need to make your class properties to public
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/
I have a string in JSON format as follows
string jsonStr = "{"Type":1, "Id":1000,"Date":null,"Group": "Admin","Country":"India","Type":1}";
I want to modify this string so that Id attribute should always be the first. The order of attributes matters.
Is there any way I can modify this string.
I tried searching google but did not find appropriate solution.
Any help would be appreciated.
EDIT:
I also tried to deserialize object using
object yourOjbect = new JavaScriptSerializer().DeserializeObject(jsonStr);
But here also the "type" attribute comes first. I dont find any way to move the attributes within this deserialized object
It's possible. Use the JsonProperty attribute, property Order.
http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm.
Let me know if it works.
Instead of attempting to manipulate the order of the outputted JSON and comparing strings, I would transform both JSON strings that you want to compare, into objects and then perform your comparison. You could then compare individual properties or entire objects with something like the following:
void CompareJSON()
{
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
string jsonToCompare = "JSON TO COMPARE";
MyObject myJsonObject = JsonConvert.DeserializeObject<MyObject>(json);
MyObject myJsonObjectToCompare = JsonConvert.DeserializeObject<MyObject>(jsonToCompare);
if (myJsonObject.Id == myJsonObjectToCompare.Id)
{
// Do something
}
}
class MyObject
{
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
Please note that this example is carried out using the Newtonsoft.JSON library. More information on the library can be found here.
Just make your JSON into a c# class with Id first and then serialize it again if that is what you need. You do know that you have "Type" twice in the JSON string? In this solution it will get "fixed" so you only have it once as it should be. But if your string really is with two Type this wont work since the strings will be incorrect. If they really are like that you need to do some ugly string manipulation to fix the order but i hope the first string is incorrect only here and not in your code.
private void Test() {
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyJsonObject myJsonObject = jsonSerializer.Deserialize<MyJsonObject>(json);
string s = jsonSerializer.Serialize(myJsonObject);
//Returns: {"Id":1000,"Type":1,"Date":null,"Group":"Admin","Country":"India"}
}
class MyJsonObject {
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
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.