2015-10-15 96 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" 
} 
相关问题