When I try to deserialize date from this string format 2022-05-18Z in Jackson it throws this exception:
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String "2022-05-18Z": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '2022-05-18Z' could not be parsed, unparsed text found at index 10
All attempts to configure Date field from this string was unsuccessful, I did:
#JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate date;
#JsonFormat(pattern = "yyyy-MM-ddZ")
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime date;
#JsonFormat(pattern = "yyyy-MM-ddZ")
private Date date;
What is the right way to deserialize this string yyyy-MM-ddZ format to Date? I believe this "Z" at the end is the timezone, is there a way to represent it in this mask?
Thanks in advance.
Ok, I found the answer. After few more attempts, finally got the solution:
#JsonFormat(pattern = "yyyy-MM-dd")
private Date date;
I have input data that contains strings that represent dates. These may be date strings like "2000-01-01", but they might say "5Y", meaning "five years". So I have a small class to keep track of these...
Public Class FlexDate
Friend Input As String = ""
Friend Value As DateTime = EarliestDate
...
You might find one of these FlexDates inside a Rent object, like "myRent.StartDate". The "problem" is that I would like the Value to be accessed as the field name. For instance...
myRent.StartDate.Input - returns a string
myRent.StartDate.Value - returns a DateTime
So what about....
myRent.StartDate - myRent.StartDate.Value
Is there any way to do this? It's sort of like a default property in a way, but with no index, so I don't think you can use that mechanism in this case?
You could specify the default property using the DefaultMemberAttribute:
<System.Reflection.DefaultMember("Value")> _
Public Class FlexDate
'...
End Class
But this won't help you in VB, because you can't access it. It is just ambiguous - do you mean the object or its property.
But you can implement an implicit conversion:
Class FlexDate
'...
Public Shared Widening Operator CType(this As FlexDate) As DateTime
Return this.Value
End Operator
End Class
Dim date As New FlexDate
Dim value As DateTime = date 'Works with the implicit operator
I am using Window Application for my project. There is situation where i need to define string enum and using it in my project.
i.e.
Dim PersonalInfo As String = "Personal Info"
Dim Contanct As String = "Personal Contanct"
Public Enum Test
PersonalInfo
Contanct
End Enum
Now i want value of that variable PersonalInfo and Contract as "Personal Info" and "Personal Contanct".
How can i get this value using ENUM? or anyother way to do it.
Thanks in advance...
For non-integer values, Const in a Structure (or Class) can be used instead:
Structure Test
Const PersonalInfo = "Personal Info"
Const Contanct = "Personal Contanct"
End Structure
or in a Module for direct access without the Test. part:
Module Test
Public Const PersonalInfo = "Personal Info"
Public Const Contanct = "Personal Contanct"
End Module
In some cases, the variable name can be used as a value:
Enum Test
Personal_Info
Personal_Contanct
End Enum
Dim PersonalInfo As String = Test.Personal_Info.ToString.Replace("_"c, " "c)
' or in Visual Studio 2015 and newer:
Dim Contanct As String = NameOf(Test.Personal_Contanct).Replace("_"c, " "c)
You could just create a new type
''' <completionlist cref="Test"/>
Class Test
Private Key As String
Public Shared ReadOnly Contact As Test = New Test("Personal Contanct")
Public Shared ReadOnly PersonalInfo As Test = New Test("Personal Info")
Private Sub New(key as String)
Me.Key = key
End Sub
Public Overrides Function ToString() As String
Return Me.Key
End Function
End Class
and when you use it, it kinda looks like an enum:
Sub Main
DoSomething(Test.Contact)
DoSomething(Test.PersonalInfo)
End Sub
Sub DoSomething(test As Test)
Console.WriteLine(test.ToString())
End Sub
output:
Personal Contanct
Personal Info
How about using Tagging. Something like:
Public Enum MyEnum
<StringValue("Personal Contact")>Contact
<StringValue("My PersonalInfo")>PersonalInfo
End Enum
You would have to write the StringValue attribute as:
Public Class StringValueAttribute
Inherits Attribute
Public Property Value As String
Public Sub New(ByVal val As String)
Value = val
End Sub
End Class
To get it out:
Public Function GetEnumByStringValueAttribute(value As String, enumType As Type) As Object
For Each val As [Enum] In [Enum].GetValues(enumType)
Dim fi As FieldInfo = enumType.GetField(val.ToString())
Dim attributes As StringValueAttribute() = DirectCast(fi.GetCustomAttributes(GetType(StringValueAttribute), False), StringValueAttribute())
Dim attr As StringValueAttribute = attributes(0)
If attr.Value = value Then
Return val
End If
Next
Throw New ArgumentException("The value '" & value & "' is not supported.")
End Function
Public Function GetEnumByStringValueAttribute(Of YourEnumType)(value As String) As YourEnumType
Return CType(GetEnumByStringValueAttribute(value, GetType(YourEnumType)), YourEnumType)
End Function
And then a call to get the Enum (using string attribute):
Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")
To get the "Attribute" value out (removed handling 'Nothing' for clarity):
Public Function GetEnumValue(Of YourEnumType)(p As YourEnumType) As String
Return DirectCast(Attribute.GetCustomAttribute(ForValue(p), GetType(StringValueAttribute)), StringValueAttribute).Value
End Function
Private Function ForValue(Of YourEnumType)(p As YourEnumType) As MemberInfo
Return GetType(YourEnumType).GetField([Enum].GetName(GetType(YourEnumType), p))
End Function
And the call to get the string attribute (using Enum):
Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)
How can i get this value using ENUM? or anyother way to do it.
There are three common ways of mapping enum values to strings:
Use a Dictionary(Of YourEnumType, String)
Decorate the enum values with attributes (e.g. DescriptionAttribute) and fetch them with reflection
Use a Switch statement
The first of these options is probably the simplest, in my view.
I know this is an old post put I found a nice solution that worth sharing:
''' <summary>
''' Gives acces to strings paths that are used often in the application
''' </summary>
Public NotInheritable Class Link
Public Const lrAutoSpeed As String = "scVirtualMaster<.lrAutoSpeed>"
Public Const eSimpleStatus As String = "scMachineControl<.eSimpleStatus>"
Public Const xLivebitHMI As String = "scMachineControl<.xLivebitHMI>"
Public Const xChangeCycleActive As String = "scMachineControl<.xChangeCycleActive>"
End Class
Usage:
'Can be anywhere in you applicaiton:
Link.xChangeCycleActive
This prevents unwanted extra coding, it's easy to maintain and I think this minimizes extra processor overhead.
Also visual studio shows the string attributes right after you type "Link"
just like if it is a regular Enum
If all you want to do is display the enums in a list or combo, you can use tagging such as
Private Enum MyEnum
Select_an_option___
__ACCOUNTS__
Invoices0
Review_Invoice
__MEETINGS__
Scheduled_Meetings0
Open_Meeting
Cancelled_Meetings0
Current_Meetings0
End Enum
Then pull the MyEnum into a string and use Replace (or Regex) to replace the tags: "___" with "...", "__" with "**", "_" with " ", and remove trailing numbers. Then repack it up into an array and dump it into a combobox which will look like:
Select an option...
**ACCOUNTS**
Invoices
Review Invoice
**MEETINGS**
Scheduled Meetings
Open Meeting
Cancelled Meetings
Current Meetings
(You can use the numbers to, say, disable a text field for inputting an invoice number or meeting room. In the example, Review Invoice and Open Meeting might be expecting additional input so a text box might be enabled for those selections.)
When you parse the selected combo item, the enumeration will work as expected but you only really need to add a single line of code - the text replacement - to get the combo to look as you wish.
(The explanation is about 10 times as involved as the actual solution!)
This technique from Microsoft - "How to: Determine the String Associated with an Enumeration Value (Visual Basic)" - will be useful in some situations (it didn't help with mine unfortunately though :( ). Microsoft's example:
VB:
Public Enum flavorEnum
salty
sweet
sour
bitter
End Enum
Private Sub TestMethod()
MsgBox("The strings in the flavorEnum are:")
Dim i As String
For Each i In [Enum].GetNames(GetType(flavorEnum))
MsgBox(i)
Next
End Sub
I am having a structure that is actually a simple byte with more functionality.
I defined it this way:
Structure DeltaTime
Private m_DeltaTime As Byte
Public ReadOnly DeltaTime As Byte
Get
Return m_DeltaTime
End Get
End Property
End Structure
I want to have these two functionalities:
Public Sub Main
Dim x As DeltaTime = 80 'Create a new instance of DeltaTime set to 80
Dim y As New ClassWithDtProperty With { .DeltaTime = 80 }
End Sub
Is there a way to achieve this?
If there would be a way to inherit from Structure I would simply inherit from Byte adding my functionality, basically I just need a byte Structure with custom functionality.
My question is also valid when you want to define your new singleton member value-types (like, you want to define a nibble-type for instance etc.) and you want to be able to set it with an assignment to number or other language typed representation.
In other words, I want to be able to do define the following Int4 (nibble) stucture and use it as follows:
Dim myNibble As Int4 = &HF 'Unsigned
Create a conversion operator, e.g.
Structure DeltaTime
Private m_DeltaTime As Byte
Public ReadOnly Property DeltaTime() As Byte
Get
Return m_DeltaTime
End Get
End Property
Public Shared Widening Operator CType(ByVal value As Byte) As DeltaTime
Return New DeltaTime With {.m_DeltaTime = value}
End Operator
End Structure
UPDATE:
For your proposed Int4 type I strongly suggest that you make it a Narrowing operator instead. This forces the user of your code to cast explicitly, which is a visual hint that the assignment might fail at runtime, e.g.
Dim x As Int4 = CType(&HF, Int4) ' should succeed
Dim y As Int4 = CType(&HFF, Int4) ' should fail with an OverflowException
I'd like to get a string representation of the underlying type of the enum.
Dim target As System.ConsoleColor = ConsoleColor.Cyan
Dim actual = 'What goes here?
Dim expected = "11"
In C# terms; you could assume int:
int val = (int) target;
string valString = val.ToString();
or if you don't want the assumption:
object val = Convert.ChangeType(target,
Enum.GetUnderlyingType(typeof(ConsoleColor)));
string valString = val.ToString();