2015-10-15 181 views
0

我使用這個代碼反序列化JSON字符串對象:嵌套的JSON字符串轉換爲自定義對象

var account = JsonConvert.DeserializeObject<LdapAccount>(result.ToString()); 

我收到此錯誤:

Error reading string. Unexpected token: StartArray. Path 'mail', line 8, position 12.

我知道這是因爲嵌套在JSON中,但不知道如何解決。我只關心我的自定義類中的屬性。

JSON字符串:

{ 
    "DN": "cn=jdoe,ou=test,dc=foo,dc=com", 
    "objectClass": [ 
    "inetOrgPerson", 
    "organizationalPerson", 
    "person" 
    ], 
    "mail": [ 
    "[email protected]" 
    ], 
    "sn": [ 
    "Doe" 
    ], 
    "givenName": [ 
    "John" 
    ], 
    "uid": [ 
    "jdoe" 
    ], 
    "cn": [ 
    "jdoe" 
    ], 
    "userPassword": [ 
    "xxx" 
    ] 
} 

我的類:

public class Account 
    { 
     public string CID { get; set; }    
     public string jsonrpc { get; set; } 
     public string id { get; set; } 
     public string mail { get; set; } 
     public string uid { get; set; } 
     public string userPassword { get; set; }    
    } 

回答

1

嗯...的JSON符號期待字符串數組或列表,但你必須期待它一個字符串。

如果您正在使用JSON.NET,你可以改變這樣的:

public class Account 
{ 
    public string CID { get; set; }    
    public string jsonrpc { get; set; } 
    public string id { get; set; } 
    public List<string> mail { get; set; } 
    public List<string> uid { get; set; } 
    public List<string> userPassword { get; set; }    
} 

應該更好地工作......

BTW,性能CIDjsonrpcid沒有在JSON相應字段本身。所以期待這些不會被填充。

1

您的JSON文件中的某些名稱/值對(如mail,uid和userpassword)定義爲arrayhttp://json.org/

howerver,Account類中的同名屬性不是數組或列表。如果你像這樣改變你的JSON文件,反序列化將會起作用。

{ 
    "DN": "cn=jdoe,ou=test,dc=foo,dc=com", 
    "objectClass": [ 
    "inetOrgPerson", 
    "organizationalPerson", 
    "person" 
    ], 
    "mail": "[email protected]", 
    "sn": "Doe", 
    "givenName": "John", 
    "uid": "jdoe", 
    "cn": "jdoe", 
    "userPassword": "xxx" 
}