.NET Web API:反序列化JSON对象,其属性为List(Of object) [英] .NET Web API : deserialize JSON object with property as List(Of object)

查看:74
本文介绍了.NET Web API:反序列化JSON对象,其属性为List(Of object)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我创建了一个像这样的Filter类……

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

如您所见,此类"Filter"包含一个"Filters"属性,该属性基本上是"FilterItem"对象的数组(实际上是一个List).

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

现在,我可以使用JSON将这个"Filter"类的实例发送到我的ASP.NET Web API,结果是:

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}]}

但是,在接收端(在Web API本身中),尽管它读出的内容完全相同(与JSON格式的字符串一样),并且可以正确转换为"Filter"对象,但具有属性"Filters"作为"FilterItem"对象的空列表!

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?

推荐答案

当我手动将JSON字符串反序列化为object时,我自己解决了这个问题:

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

显然,我只是在"FilterItem"类中缺少了(无参数) New()构造函数.

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

这篇关于.NET Web API:反序列化JSON对象,其属性为List(Of object)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆