.NET Web API : deserialize JSON object with proper

2019-09-10 16:21发布

Imagine I created a Filter class like this......

Public Class Filter

    Public Enum enuOperator
        [EqualTo] = 0
        [Like] = 1
        [In] = 2
        [StartsWith] = 3
        [EndsWith] = 4
        [NotNull] = 5
        [Null] = 6
    End Enum

    Public Class FilterItem

        Public Property [Field] As String
        Public Property [Operator] As enuOperator
        Public Property [Value] As Object

        Public Sub New(filterField As String, filterOperator As enuOperator, filterValue As Object)
            With Me
                .Field = filterField
                .Operator = filterOperator
                .Value = filterValue
            End With
        End Sub

        Public Sub New(filterField As String, filterValue As Object)
            Me.New(filterField, enuOperator.EqualTo, filterValue)
        End Sub

    End Class

    Public Property Filters As List(Of FilterItem)

    Public Sub New()
    End Sub

    Public Sub New(filterItems As List(Of FilterItem))
        Me.Filters = filterItems
    End Sub

End Class

As you can see, this class "Filter" contains a property "Filters", which is basically an array (a List, actually) of "FilterItem" objects.

Now, I can send an instance of this "Filter" class to my ASP.NET Web API, using JSON, resulting in this notation :

{"Filters":[{"Field":"PrTy_Id","Operator":0,"Value":3}]}

However, on the receiving side (in the Web API itself), although it reads out exactly the same (as a JSON-formatted string), and it correctly converts to a "Filter" object, but with property "Filters" as an empty List of "FilterItem" objects!

Obviously my question is, how can I read out the "Filters" property, and correctly convert it to an existing List of objects?

1条回答
Bombasti
2楼-- · 2019-09-10 16:43

Figured it out myself, when manually deserializing my JSON string to object :

Apparently, I was simply missing an empty (no arguments) New() constructor in the "FilterItem" class.

查看更多
登录 后发表回答