Reputation: 817
I'm sure this has been asked but I'm unable to find it maybe because I don't know what the terms of it would be. Let's say I have the following:
JSON
{
"Field1": 1234,
"Field2": 5678,
"MoreData": {
"Field3": 9012,
"Field4": 3456
},
"Field5": "Test"
}
Class
public class Sample()
{
public int Field1 { get; set; }
public int Field2 { get; set; }
public int Field3 { get; set; }
public int Field4 { get; set; }
public string Field5 { get; set; }
}
If I deserialize this Field1, Field2, and Field5 will be populated but is there a way to also get Field3 and Field4 populated in an easy way.
I don't want to have a public class MoreData for Field2 and Field3.
Upvotes: 1
Views: 2208
Reputation: 467
If you are unable to change models then try this:
public class SampleContractResolver : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public CustomContractResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{"Field3", "MoreData.Field3"},
{"Field4", "MoreData.Field4"},
};
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
And use this like this:
var sample = JsonConvert.DeserializeObject<Sample>(json, new JsonSerializerSettings(){
ContractResolver = new SampleContractResolver()
});
Upvotes: 2
Reputation: 817
Thank you to @Artur for offering this link Can I specify a path in an attribute to map a property in my class to a child property in my JSON? this worked perfectly.
You will have to use NewtonJson and not Microsoft's System.Text.Json to get this to work.
Once you create the class from the link above you can do the following.
{
"Field1": 1234,
"Field2": 5678,
"MoreData": {
"Field3": 9012,
"Field4": 3456
},
"Field5": "Test"
}
[JsonConverter(typeof(JsonPathConverter))]
public class Sample()
{
public int Field1 { get; set; }
public int Field2 { get; set; }
[JsonProperty("MoreData.Field3")]
public int Field3 { get; set; }
[JsonProperty("MoreData.Field4")]
public int Field4 { get; set; }
public string Field5 { get; set; }
}
Upvotes: 0
Reputation: 11364
You can use the setter to set your Field3 and Field4 values.
public class Sample
{
public int Field1 { get; set; }
public int Field2 { get; set; }
public int Field3 { get; set; }
public int Field4 { get; set; }
public string Field5 { get; set; }
public dynamic MoreData {
set {
Field3 = value.Field3;
Field4 = value.Field4;
}
}
}
When you deserialize your Json above, you'll get the values copied to Field3 and Field4 of the Sample class as well.
Removed the MoreData class as per your requirement. You can use dynamic type to look up the variables for the MoreData object.
Upvotes: 0