0

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).

fso
  • 144
  • 2
  • 14

3 Answers3

3
var point = new { X = 0.0f, Z = 0.0f };
var jsonResponse = 
    JsonConvert.DeserializeAnonymousType(json, point);
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • Thanks for tour answer, but this is not what I am looking for. I want to use an existing type as template and deserialize the json provided properties into an anonymous object. **Please, do not vote up.** – fso Aug 22 '17 at 09:19
  • @fso the answer does exactly what you are asking. Can you please clarify how this does not answer your question and we can see if we can address that. – CodingYoshi Aug 22 '17 at 12:22
  • _the answer does exactly what you are asking_ --> NO 1) I do not want to instanciate an anonymous type before deserialization. 2) The _template_ type used for deserialization should be **static** and should be used as a _mask_ and for the properties type validation. – fso Aug 22 '17 at 15:03
  • @fso You only need to instantiate the anonymous type so it can be used as a template; anonymous types have no class so it needs this to be used as a type. There is no other way to do it. – CodingYoshi Aug 22 '17 at 15:16
1

No, there is no way to do this unless you use code generation. Anonymous types are defined at compile time, whereas you are saying you don't know what properties you want in the anonymous type until you get the JSON (at run time).

If you're just trying to detect which properties were present in the JSON or not, you could deserialize into a JObject and then process that to figure out what changed. Alternatively, you could add a status dictionary to your model and then deserialize to it using a JsonConverter. See Is there a way in Json.NET serialization to distinguish between "null because not present" and "null because null"? for examples of these ideas.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • Thanks, I just wanted to know if I need to write my own converter with or without some expression magic, this is not part of the Json.net library so I will implement it myself. PS: ty for the link. – fso Aug 22 '17 at 21:13
1

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.

fso
  • 144
  • 2
  • 14