JSON Parser Xojo plugin

JSONPrimitive.ToVariant Method

Attempts to convert the JSON structure to variant. Taking optional delegate to evaluate custom structures such as color and date which are not part of normal JSON standard.

ToVariant(
   stringEvaluator as EvaluateStringDelegate) as Variant

Parameters

stringEvaluator
Optional parameter to evaluate custom structures such as for example Date or Color.

Returns

Variant

Remarks

Custom structure check:


d = jp.ToVariant(AddressOf CheckForDate) // Note passing in Delegate here is optional




Public Function CheckForDate(value as String) as Variant
if Len(value) = 25 then
    if value.Mid(5,1) = "-" and value.Mid(8,1) = "-" and value.Mid(11,1) = "T" and value.Mid(14,1) = ":" and value.Mid(17,1) = ":" and value.Mid(23,1) = ":" then
       Dim d as Date = new Date()
       d.Year = Val(value.Mid(1,4))
       d.Month = Val(value.Mid(6,2))
       d.Day = Val(value.Mid(9,2))
       d.Hour = Val(value.Mid(12,2))
       d.Minute = Val(value.Mid(15,2))
       d.Second = Val(value.Mid(18,2))
      
       if value.Mid(20, 1) = "+" then
          d.GMTOffset = Val(value.Mid(21,2)) + (Val(value.Mid(24,2)) / 60.0)
       else
          d.GMTOffset = (Val(value.Mid(21,2)) + (Val(value.Mid(24,2)) / 60.0)) * -11.0
       end if
      
       return d
    end if
end if

return value
End Function



Or if you are working with new style DateTime objects:

Public Function CheckForDateTime(value as String) as Variant
if Len(value) = 25 then
   
    if value.Mid(5,1) = "-" and value.Mid(8,1) = "-" and value.Mid(11,1) = "T" and value.Mid(14,1) = ":" and value.Mid(17,1) = ":" and value.Mid(23,1) = ":" then
       Dim tz as TimeZone
       Dim timeZoneDelta as Integer = (Val(value.Mid(21,2)) * 60 + Val(value.Mid(24,2))) * 60
      
       if value.Mid(20, 1) = "-" then
          timeZoneDelta = timeZoneDelta * -1
       end if
      
       tz = new TimeZone(timeZoneDelta)
      
       try
          Dim d as DateTime = new DateTime( _
             Val(value.Mid(1,4)), _
             Val(value.Mid(6,2)), _
             Val(value.Mid(9,2)), _
             Val(value.Mid(12,2)), _
             Val(value.Mid(15,2)), _
             Val(value.Mid(18,2)), _
             0, _
             tz)
         
          return d
       catch
       // Guess we did not have valid date so we return the string
       return value
    end try
   
   
end if
end if

return value
End Function

See Also

JSONPrimitive Class