regex - JSON.NET: Get Specific JSON Date Value -
in vb.net project, using json.net, i've got json web api has value representing date in yyyy-mm-ddthh:mm:ss
format, , i'd value.
here's more or less json looks like:
{ "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", }
so should serialize , value, right? however, when put key-value in variable, date format automatically changed!
dim temp string = myjsonresult("req_date") ' temp = "1/17/2016 12:27:57 pm"
i need have date retrieved json. see 2 ways go problem: converting yyyy-mm-ddthh:mm:ss
manually, or using regex directly grab key-value pair - both of have had no success with.
my attempt convert datetime:
dim tempdatetime datetime = datetime.parseexact(myjsonresult("req_date").tostring,"yyyy-mm-dd hh:mm:ss", cultureinfo.invariantculture) ' error: string not recognized valid datetime dim mydesiredresult string = tempdatetime.tostring("yyyy-mm-ddthh:mm:ss")
my attempt use regex:
dim regex regex = new regex("""req_date"": ""([\d\w]*)""") dim match match = regex.match(myjsonasstring) if match.success dim mydesiredresult string = match.groups(1).value end if ' match empty...
any , appreciated.
i assume myjsonresult
jobject
have loaded json.
your difficulty json.net automatically recognizes strings dates when reading , converts them datetime
structs. when later tostring()
on value token, comes in c#'s "invariant culture" format rather original format, in case iso 8601. if not want behavior, can parse 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() { _ .dateparsehandling = dateparsehandling.none _ } dim myjsonresult = jsonconvert.deserializeobject(of jobject)(jsonstring, settings) dim datevalue = myjsonresult("req_date") dim datestring = ctype(datevalue, string) 'value 2016-01-17t12:27:57
there's no overload jobject.parse()
takes jsonserializersettings
, need use deserializeobject
. setting gets propagated jsonreader.dateparsehandling
.
alternatively, if ok json.net recognizing dates them printed in iso 8601 format, can re-serialize token json rather getting string value:
dim datevalue = myjsonresult("req_date") dim datestring = jsonconvert.serializeobject(datevalue).trim(""""c) 'value 2016-01-17t12:27:57
prototype fiddle. related c# question.
Comments
Post a Comment