如何反序列化嵌套对象?

时间:2013-02-08 17:29:55

标签: c# json serialization

我设法通过创建数据合同类(在向客户唠叨一公吨之后)创建反序列化。我的问题是我声明的两个字段都返回空的东西。所以,我已经看过它,并意识到JSON对象是嵌套的,我不清楚如何访问内部的部分。

数据合约是这样的,但我将 Bopp 视为空(或空字符串,不确定是哪个), Mopp 是一堆零。

[DataContract]
public class Customer
{
  [DataMember(Name = "Beep")]
  public String Bopp;

  [DataMember(Name = "Meep")]
  public Guid Mopp;
}

认为数据在此表单上。

[
  {"Beep":"beep1", "Meep":"meep1"},
  {"Beep":"beep2", "Meep":"meep2"},
  {"Beep":"beep3", "Meep":"meep3"}
]

然而,显然,他们将对象移到中,所以它更像是这样。

[ "root":[
  {
    "A":"some",
    "B":[
      {"Beep":"beep1", "Meep":"meep1"},
      {"Beep":"beep2", "Meep":"meep2"},
      {"Beep":"beep3", "Meep":"meep3"}],
    "C":"some"
  },
  {
    "A":"some",
    "B":[
      {"Beep":"beep1", "Meep":"meep1"},
      {"Beep":"beep2", "Meep":"meep2"},
      {"Beep":"beep3", "Meep":"meep3"}],
    "C":"some"
  }
]]

如何重新设计数据合同以使其访问正确的字段?或者我错过了什么,数据成员的名称必须与字段不同(即 Beep Bopp 不起作用)?!

编辑:

根据要求,我会从字符串中发布(几乎)实时数据。

{"CustomerStatuses":[{
  "Information":[{"Guid":"1","Role":"Customer"}],
  "CustomerId":"12345678-1234-1324-1234-123456781234",
  "Status":4},
  "Information":[{"Guid":"5","Role":"Customer"}],
  "CustomerId":"12345678-1234-1324-1234-123456781234",
  "Status":6},
  "Information":[{"Guid":"7","Role":"Seller"}],
  "CustomerId":"12345678-1234-1324-1234-123456781234",
  "Status":6},
  ...

这是实际的数据合同。

[DataContract]
public class Customer
{
  [DataMember(Name = "Status")]
  public String Status;

  [DataMember(Name = "CustomerId")]
  public Guid Guid;
}

1 个答案:

答案 0 :(得分:0)

您的类结构需要与Json匹配:

<DataContract> 
Public Class Customer 

<DataMember(Name:="Status")> 
Public Property Status As Int32 

<DataMember> 
Public Property Information As Object 

<DataMember> 
Public Property CustomerId As String 

End Class 




Public Class Customers 

Public Property CustomerStatuses As List(Of Customer) 

End Class