Json.Net Serialized Object Losing Id

I am using Json.Net to serialize and deserialize an object.

I am having a problem where a deserialized recordPosted object has a null value as an identifier.

While the serialized record will contain the identifier 180

JsonSerializerSettings jsSettings = new JsonSerializerSettings(); jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; var recordAsJson = JsonConvert.SerializeObject(recordToUpdate, Formatting.None, jsSettings); //recordAsJson = {"Id":180,.... var recordPosted = JsonConvert.DeserializeObject<record>(recordAsJson); //recordPosted = Id : 0 

How can i solve this?

Edit

 public virtual int Id { get; private set; } 
+6
source share
2 answers

Json.NET by default does not install property setting tools. Either make the setter public, or put the [JsonProperty] attribute in the property.

+14
source

You are not showing record , but I would say that you have something like:

 private int id; public int Id { get { return id; } } 

there is not much that the serializer can do here to set Id , so ... it is not. Note: some serializers (for example, t23>) will also refuse to serialize such ones, but JSON serializers tend to be more forgiving, since quite often use only serialization to return data from the web server to the javascript client, including from anonymous types ( which are immutable in C #).

You can try to have a private set :

 private int id; public int Id { get { return id; } private set { id = value; } } 

(or alternatively)

 public int Id { get; private set; } 

If this still does not work - perhaps it should be fully public:

 private int id; public int Id { get { return id; } set { id = value; } } 

(or alternatively)

 public int Id { get; set; } 
+1
source

Source: https://habr.com/ru/post/897379/


All Articles