0

I have a problem where I would like to be able to convert a json path into an object path based on the model used by Newtonsoft.Json to map between json and an my c# object model.

Below I have an example of some complex types that are serialised into json. Given I have the json path of a child property my_child.uppercase, I would like to convert that into the object property path Child.Uppercase.

Is it possible to query the model used by Newtonsoft.Json to map between the two worlds? Or do i have to build it from scratch using reflection?

public class ParentModel
{
   // serialised into another name!
   [JsonProperty(PropertyName = "my_child")]
   public ChildModel Child {get; set;} 
}

//serialised into another case!
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class ChildModel
{
   public string Uppercase {get; set;} 
}

void Main()
{
    var item = new ParentModel() {
        Child = new ChildModel() {
            Uppercase = "Joe"
        }
    };

    // outputs {"my_child":{"uppercase":"Joe"}}
    JsonConvert.SerializeObject(item).Dump();

    var expected = "Child.Uppercase";
    var actual = ConvertJsonPropertiesToObjectProperties("my_child.uppercase");

    Debug.Assert(expected == actual);
}

string ConvertJsonPropertiesToObjectProperties(string jsonPropertyNames){
    return "implement me!!";
}
alastairtree
  • 3,960
  • 32
  • 49
  • I think your options are to use reflection, or to query the serialized object using `SelectToken`. I've run into this before and ended up using reflection. See: https://stackoverflow.com/questions/33088462/can-i-specify-a-path-in-an-attribute-to-map-a-property-in-my-class-to-a-child-pr –  Mar 20 '19 at 18:09
  • That link is helpful, thanks, but I am really after the mapping model rather than the actual serialised property data - I need to be able convert the json property path into the object property path, not access the value in the json itself. – alastairtree Mar 20 '19 at 18:16
  • I'm not aware of any kind of mapping model you can use. Entity Framework has such models, but I don't think Newtonsoft does. I could probably adapt the converter in that link for your purposes, but not until this evening. –  Mar 20 '19 at 18:18

0 Answers0