JSON.NET: Get Specific JSON Date Value

后端 未结 3 1118
无人共我
无人共我 2020-12-12 04:27

In my VB.NET project, using JSON.NET, I\'ve got a JSON from a Web API that has a value representing a date in the yyyy-MM-ddTHH:mm:ss format, and I\'d like to s

3条回答
  •  误落风尘
    2020-12-12 04:55

    I assume that myJsonResult is a JObject into which you have loaded your JSON.

    Your difficulty is that Json.NET automatically recognizes strings as dates when reading and converts them to DateTime structs. Then when you later do ToString() on the value token, it comes back in c#'s "invariant culture" format rather than the original format, which in this case was ISO 8601. If you do not want this behavior, you can parse your JSON using JsonSerializerSettings.DateParseHandling = DateParseHandling.None:

            Dim jsonString = "{'REQ_DATE':'2016-01-17T12:27:57','REQ_TYPE':'Vacation','HOURS':500.0,'LEAVE_TIME':'8:00 AM','LEAVE_DATE':'2016-01-23T00:00:00','DUE_TIME':'8:00 AM','DUE_DATE':'2016-01-24T00:00:00'}"
            Dim settings = New JsonSerializerSettings() With { _
                .DateParseHandling = DateParseHandling.None _
            }
            Dim myJsonResult = JsonConvert.DeserializeObject(Of JObject)(jsonString, settings)
            Dim dateValue = myJsonResult("REQ_DATE")
            Dim dateString = CType(dateValue, String) 'Value is 2016-01-17T12:27:57
    

    There's no overload to JObject.Parse() that takes a JsonSerializerSettings, so you would need to use DeserializeObject. This setting eventually gets propagated to JsonReader.DateParseHandling.

    Alternatively, if you are OK with Json.NET recognizing dates but would always like them to be printed in ISO 8601 format, you can re-serialize the token to JSON rather than just getting the string value:

            Dim dateValue = myJsonResult("REQ_DATE")
            Dim dateString = JsonConvert.SerializeObject(dateValue).Trim(""""c) 'Value is 2016-01-17T12:27:57
    

    Prototype fiddle. Related c# question.

提交回复
热议问题