Home > front end >  How to convert dynamic property to string
How to convert dynamic property to string

Time:09-26

I have some dynamic object, data:

{
    ...
    "start": "2022-09-24T04:04:00Z",
    ...
}

and I want to get the string value "2022-09-24T04:04:00Z" into a variable. Whenever I try casting, or printing or data.ToString etc, the string is automatically formatted to "24/09/2022 4:04:00 AM".

How can I convert this dynamic property to a string without changing its format?

It looks like it's being interpreted as a datetime, and then calling DateTime.ToString on it, which must convert the format.

The dynamic comes from JsonConvert.DeserializeObject<dynamic> btw.

CodePudding user response:

You can turn off DateTime handling via JsonSerializerSettings:

static void Main(string[] args)
{
    var json = "{\"start\": \"2022-09-24T04:04:00Z\"}";
    var settings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None };
    var result = JsonConvert.DeserializeObject<dynamic>(json, settings);
    Console.WriteLine(result["start"]);
    Console.ReadLine();
}

CodePudding user response:

string data="....";
dynamic dynamicData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(data);
string date = dynamicData.start.ToString();
  • Related