Reputation: 385
I am using Newtonsoft JSON Serialization(packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll) to convert the string to Class Domain in C#. but when i created a domain with Get / Set property. It is not converted.
public class Account
{
private string _Email = string.Empty;
private bool _Active = false;
private DateTime _CreatedDate = new DateTime();
private IList<string> _Roles = new List<string> ();
public string Email { get => _Email; set => value = _Email; }
public bool Active { get => _Active; set => value = _Active; }
public DateTime CreatedDate { get => _CreatedDate; set => value = _CreatedDate; }
public IList<string> Roles { get => _Roles; set => value = _Roles; }
}
Running code,
string json = @"{
'Email': '[email protected]',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account1 = JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
Result:
The list(roles) is converted from string. but, remaining columns, it is not converted. Screen added FYR:
Upvotes: 0
Views: 222
Reputation: 12806
It is not getting converted because you are assigning the value
with your backing field, while it should be upside down.
You are currently doing this
public string Email { get => _Email; set => value = _Email }
This is incorrect, if you really want to use backing fields, then do it like
public string Email { get => _email; set => _email = value; }
(also note, that I changed the backing field to Camel Cased, which is more up to date with coding conventions in C#)
The reason that it works with a list, is that NewtonSoft sees a list, and simply adds the items to your list (it only does a get, but no set)
In fact, you don't need any of the backing fields, you can just solve it through auto properties
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; } = new List<string>();
}
Upvotes: 3