0

I have a JSON object that looks like this:

{
    "Name": "John Smith"
    "Age": 18
    "Children" : [
        {
            "Name": "Little Johnny"
            "Age": 4
            "Children": []
        }
    ]
}

My Model object looks like this

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
    public IList<Person> Children { get; set; }
    public Guid? TrackingKey { get; set; }
}

As you see the "TrackingKey" property is not a part of the JSON.

I want to have the TrackingKey property to be set with a value that I provide upon JSON deserialization.

The tracking key will be the same for the parent and all the children as well.

However it cannot be a static value that i could pass in with the DefaultValue attribute when I declare my model.

What would be the best way to assign The Tracking Key to a collection of parents and ALL their children?

Nandun
  • 1,802
  • 2
  • 20
  • 35
  • First of all, why do you need to define tracking id? – Derviş Kayımbaşıoğlu Mar 01 '19 at 18:58
  • does the logic to generate the TrackingKey involve external data other than the data in the Person object? – Matt.G Mar 01 '19 at 19:34
  • @Matt.G - yes tracking key is external – Nandun Mar 01 '19 at 19:35
  • I'm afraid there is no direct way of setting the TrackingKey during deserialization (apart from a static value using the DefaultValue attribute). you could set it after the deserialization – Matt.G Mar 01 '19 at 19:36
  • @Matt.G - that was my backup plan too. i'm wondering if there was any delegate or arrow function etc. that can be used to "transform" an object post deserialization. or i will need to recursively loop every item in my collection to add the tracking key which i'm trying to avoid. – Nandun Mar 01 '19 at 19:39
  • there are 4 callbacks as explained [here](https://www.newtonsoft.com/json/help/html/SerializationCallbacks.htm). But might not help your requirement – Matt.G Mar 01 '19 at 19:42
  • You could use a `[ThreadStatic]` member to pass data into your object constructors, for instance as shown in [Execute code to custom type after deserializing an object from Xml](https://stackoverflow.com/q/29438151/3744182). – dbc Mar 02 '19 at 00:34

1 Answers1

0

You can use GUIDs to generate the value you need.

      string dados = Guid.NewGuid().ToString("N");
Alberto Santos
  • 357
  • 1
  • 9
  • I'm not looking to generate a new Guid in this case. I already have a guid that was generated elsewhere. i need to assign it to all my deserialized objects. – Nandun Mar 01 '19 at 20:47