在VB.Net WebMethod中反序列化JSON无法正常工作

时间:2018-08-14 16:02:11

标签: asp.net json vb.net webmethod json-deserialization

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

我的对象类:

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

public class Attribute
{
    public string Category { get; set; }
    public string Value { get; set; }

}

这是我的WebMethod:

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

我的问题是,我得到了7个具有“类别”和“值”标签的属性数组,但是值是“ Nothing”。我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您的对象模型与实际映射到以下内容的显示的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
相关问题