Search code examples
c#json.netdeserializationjson-deserialization

Partial deserialization with Json.net


Is there an existing way with Json.net to deserialize a json string into an anonymous object (which has the json properties only) using a concrete type as template ?

Exemple

JSON:

{ X: 1, Z: 2 }

Model:

public class Point {
    public float X { get; set; }
    public float Y { get; set; }
    public float Z { get; set; }
}

Desired deserialized ouput anonymous object :

new { X=1.0f, Z=1.0f } //Please note that X & Z are typed according to the Point class.

I want to do something like :

var @object = serializer.DeserializeAsAnonymous<Point>(json);

Why? I want to detect which properties of the model to update using reflection on both sides (model and provided deserialized json).


Solution

  • serializer.Populate is the method I was looking for... It doesn't produce an anonymous object, but it populates an existing object with the existing json properties.