Home > Mobile >  Why does a property in an object need to be set and not private set when using newtonsoft.Json
Why does a property in an object need to be set and not private set when using newtonsoft.Json

Time:02-17

I recenlty made a register and came upon a problem whereby this line below wouldnt work unless my properties in my person object were set and not private set

AllPeopleAdded.AddRange(JsonConvert.DeserializeObject<List<Person>>(File.ReadAllText(jsonfilePath)));

When I say doesnt work I mean that the JsonConvert.DeserializeObject returns null values to my the list.

The person class has 2 properties

        public string mFirstName {get;set; }
        public string mLastName {get;set; }

Is there a reason why?

CodePudding user response:

you can still make your property private but you need to add attributes. This will be working properly

public class Person
{
    [JsonProperty]
    public string mFirstName { get; private set; }
    [JsonProperty]
    public string mLastName { get; private set; }
}

even this will be working, but it doesn't make much use

public class Person
{
    [JsonProperty]
    private string mFirstName;
    [JsonProperty]
    private string mLastName;

}
  • Related