Background
I have an application that returns an array of Config models from a SQL database. This Config model contains a string property called "CustomConfig" which holds raw JSON specific to each row. The model also contains a JObject property called "CustomConfigObject" which is essentially a deserialized version of the JSON string. This was done in order to keep the SQL Table design simple.
The ultimate point of these rows is to form a large JSON blob used to configure a client experience.
The problem
When all of the post processing has been performed on the Config models, they are then serialised using Newtonsoft.
Upon serialization, the object looks like this -
{
id: 0,
name: "Title",
customConfigObject: {
items: [...],
href: "http://...",
header: "",
orientation: 0,
apiKey: 123
}
}
I am wondering if there is a way of extracting the value of the property during serialization so that the result looks like this instead (notice there is no "customConfigObject") -
{
id: 0,
name: "Title",
items: [...],
href: "http://...",
header: "",
orientation: 0,
apiKey: 123
}
I have looked into Custom Convertors but I'm not sure it produces the needed outcome.
Any help on this one would be hugely appreciated as out current workaround is to define each possible property of "CustomConfigObject" with a getter to return the sub-property.
Many thanks!
Basic example of the issue -
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var parent = new Config(){
Name = "Parent",
Description = "desc",
Children = new List<Config>()
};
var child1 = new Config(){
Name = "Child",
Description = "desc",
CustomConfig = "{ href: 'http://...', header: '...', orientation: 0, apiKey: 123 }"
};
var child2 = new Config(){
Name = "Child 2",
Description = "desc",
CustomConfig = "{ href: 'http://...', header: 'things', orientation: 1, apiKey: 345 }"
};
parent.Children.Add(child1);
parent.Children.Add(child2);
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
var json = JsonConvert.SerializeObject(parent, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
});
Console.WriteLine(json);
}
}
public class Config{
public string Name { get; set; }
public string Description { get; set; }
[JsonIgnore]
public string CustomConfig { get; set; }
public JObject CustomConfigObject
{
get
{
if (!string.IsNullOrEmpty(CustomConfig))
{
return JObject.Parse(CustomConfig);
}
return null;
}
}
public List<Config> Children { get; set; }
}