2014-09-10 111 views
0

我有一個JSON字符串,它看起來像下面,DataContractJsonSerializer反序列化JSON

{ 
    "ErrorDetails":null, 
    "Success":true, 
    "Records":[ 
       { 
       "Attributes":[ 
           { 
            "Name":"accountid", 
            "Value":null 
           }, 
           { 
            "Name":"accountidname", 
            "Value":null 
           } 
       ], 
       "Id":"9c5071f7-e4a3-e111-b4cc-1cc1de6e4b49", 
       "Type":"contact" 
       } 
    ] 
} 

我用下面的反序列化這個字符串,

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(JSONPackage)); 
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream()); 
JSONPackage jsonResponse = objResponse as JSONPackage; 

而且我JSONPackage看起來像以下,

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace CommonLibs.JSONObjects 
{ 
    public class JSONPackage 
    { 
     public string ErrorDetails { get; set; } 
     public string Success { get; set; } 
     public List<Record> Records { get; set; } 
    } 
} 

和記錄看起來像這樣,

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.Text; 
using System.Threading.Tasks; 

namespace CommonLibs.JSONObjects 
{ 
    public class Record 
    { 
     public List<Attributes> Attributes { get; set; } 
     public string Id { get; set; } 
     public string Type { get; set; } 
    } 
} 

屬性的樣子,

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.Text; 
using System.Threading.Tasks; 

namespace CommonLibs.JSONObjects 
{ 
    public class Attributes 
    { 
     public AttributeItem AttributeItem { get; set; } 
    } 
} 

而且最後AttributeItem如下所示,

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.Text; 
using System.Threading.Tasks; 

namespace CommonLibs.JSONObjects 
{ 
    public class AttributeItem 
    { 
     public string Name { get; set; } 
     public string Value { get; set; } 
    } 
} 

然而,這似乎並不工作。

當我這樣做,

Console.WriteLine(jp.Records[0].Attributes[0].AttributeItem.Name); 

我得到一個NullPointerException(jp是JSONPackage對象)。

但是,如果我這樣做,

Console.WriteLine(jp.Records[0].Attributes.Count) i get "2" 

能否請您協助?

回答

1

您不需要Attributes類。

變化

public List<Attributes> Attributes { get; set; }

public List<AttributeItem> Attributes { get; set; }

相關問題