I am using Json.Net to serialize and deserialize an object.
I am experiencing an issue where the deserialized object recordPosted has zero as its Id.
Whereas the Serialized record will contain an Id of 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 would I resolve this?
Edit
public virtual int Id { get; private set; }
Json.NET doesn't set private property setters by default. Either make the setter public or place a [JsonProperty] attribute on the property.
You don't show record
, but I would wager that you have something like:
private int id;
public int Id { get { return id; } }
there isn't much that the serializer can do here to set Id
, so... it doesn't. Note: some serializers (XmlSerializer
, for example) will also refuse to serialize such, but JSON serializers tend to be more forgiving, since it is pretty common to use only the serialize, to return data from a web-server to a javascript client, including from anonymous types (which are immutable in C#).
You could try having 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 that still doesn't work - it may have to be fully public:
private int id;
public int Id { get { return id; } set { id = value; } }
(or alternatively)
public int Id { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With