0

I have a JSON content like this

"started_on": "2017-12-01",
"start_time": "2017-12-01T10:00:00+00:00",
"finish_time": "2017-12-01T11:00:00+00:00",

I want to read the start time and end time as a string in same format and i tried the below code for doing the same

 JObject _task = JObject.Parse(response_json);
 string _description = "\n start_time:" + (string)_task["start_time"];
 _description += "\n finish_time:" + (string)_task["finish_time"];

This reads from JSON correctly , but when i check the datetime format i can see this as like "12/01/2017" only. How can i keep the same format while doing the conversion and i want the text as it is in the JSON parameter

1 Answer 1

2

You need to instruct JSON.NET to read them as strings:

var settings = new JsonSerializerSettings
{
    DateParseHandling = DateParseHandling.None
};
JObject _task = JsonConvert.DeserializeObject<JObject>(response_json, settings);

If you need to get some of the values as DateTime objects after they have all been read as strings, you can use this:

var dt = _task["property"].Value<DateTime>();

Although at this stage you may just want to create a class to represent your JSON:

public class MyTask
{
    public DateTime Property1 {get;set;} // property1 will be read as a DateTime
    public string Property2 {get;set;} // property2 will be read as a string
}
MyTask _task = JsonConvert.DeserializeObject<MyTask>(response_json);
Sign up to request clarification or add additional context in comments.

2 Comments

can we set this on a property level. Since some other datetimes , i have to read the way it is now
@Jbin If you create a class to represent your JSON, you can choose between string and DateTime for the property type accordingly. Alternatively, you can call _task["propertyIWantAsDate"].Value<DateTime>() to convert the string into a DateTime for the properties where you need that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.