将嵌套的 json 字符串转换为自定义对象

Convert nested json string to custom object

我正在使用此代码将 json 字符串反序列化为一个对象:

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

我收到此错误:

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

我知道是因为json中的嵌套,但不知道如何解决。我只关心自定义 class 中的属性。

Json 字符串:

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

我的class:

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; }            
    }

嗯...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; }            
}

应该会更好...

顺便说一句,属性 CIDjsonrpc id 在 JSON 本身中没有相应的字段。所以希望这些不会被填充。

您的 JSON 文件中的某些 name/value 对,如邮件、uid、用户密码被定义为 arrayhttp://json.org/

然而,Account class中的同名属性不是数组或列表。如果您像这样更改 JSON 文件,反序列化将起作用。

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