Search code examples
c#jsonjson-deserialization

Convert nested json string to custom object


I am using this code to deserialize json string into an object:

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

I am getting this error:

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

I know it is because of the nesting in the json, but not sure how to resolve. I only care about the properties in my custom class.

Json string:

{
  "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"
  ]
}

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

Solution

  • Hmm... the JSON notation is expecting an array or list of strings, but you have it expecting a single string.

    If you are using JSON.NET, you could change it like this:

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

    Should work better...

    BTW, the properties CID, jsonrpc id do not have corresponding fields in the JSON itself. So expect these to not get populated.