代码之家  ›  专栏  ›  技术社区  ›  crackedcornjimmy

在VB.Net WebMethod中反序列化JSON不起作用

  •  1
  • crackedcornjimmy  · 技术社区  · 8 年前

    我在调用WebMethod时试图反序列化JSON对象。反序列化成功地创建了对象数组,但值为“Nothing”。我做错什么了?

    public class Data
    {
        public Attribute[] Attributes{ get; set; }
    }
    
    public class Attribute
    {
        public string Category { get; set; }
        public string Value { get; set; }
    
    }
    

    这是我的网络方法:

    <System.Web.Services.WebMethod()>
    Public Shared Function A_Method(ByVal Attributes As Data)
        'do things
    End Function
    

    下面是传递给WebMethod的JSON对象:

    {"Attributes":[
       {
          "Attribute":{
             "Category":"Category1",
             "Value":"Value1"
          }
       },
       {
          "Attribute":{
             "Category":"Category2",
             "Value":"Value2"
          }
       },
       {
          "Attribute":{
             "Category":"Category3",
             "Value":"Value3"
          }
       },
       {
          "Attribute":{
             "Category":"Category4",
             "Value":"Value4"
          }
       },
       {
          "Attribute":{
             "Category":"Category5",
             "Value":"Value5"
          }
       },
       {
          "Attribute":{
             "Category":"Category6",
             "Value":"Value6"
          }
       },
       {
          "Attribute":{
             "Category":"Category7",
             "Value":"Value7"
          }
       }
    ]
    }
    

    1 回复  |  直到 8 年前
        1
  •  2
  •   Nkosi    8 年前

    您的对象模型与显示的JSON不匹配,JSON实际上映射到以下内容

    public class Data {        
        public AttributeElement[] Attributes { get; set; }
    }
    
    public class AttributeElement {        
        public Attribute Attribute { get; set; }
    }
    
    public class Attribute {        
        public string Category { get; set; }        
        public string Value { get; set; }
    }
    

    注意数组中的元素如何 Attribute 财产。

    <System.Web.Services.WebMethod()>
    Public Shared Function A_Method(ByVal data As Data)
        'do things
        Dim someAttribute = data.Attributes(0).Attribute
        Dim category = someAttribute.Category
        Dim value = someAttribute.Value
        '...
    End Function