Search code examples
c#jsonjson.net

Json.NET serialize property on the same level


I have a very long and complex JSON to send to an external web service.
The JSON has all the properties at the same level:

public class Request
{
    [JsonProperty(PropertyName = "prop1a")]
    public string Prop1A;

    [JsonProperty(PropertyName = "prop2a")]
    public string Prop2A;
    
    [JsonProperty(PropertyName = "prop3a")]
    public string Prop3A;
    
    [JsonProperty(PropertyName = "prop1b")]
    public string Prop1B;

    [JsonProperty(PropertyName = "prop2b")]
    public string Prop2B;
    
    [JsonProperty(PropertyName = "prop3b")]
    public string Prop3B;
    
    // [...]
}

The resulting JSON:

// valid JSON
{ prop1a: "", prop2a: "", prop3a: "", prop1b: "", prop2b: "", prop3b: "" }

In order to work better I have logically separated similar properties into smaller classes:

public class Request
{
    public AggregatedPropsA MyAggregatedPropsA;
    
    public AggregatedPropsB MyAggregatedPropsB;
}

public class AggregatedPropsA
{
    [JsonProperty(PropertyName = "prop1a")]
    public string Prop1A;

    [JsonProperty(PropertyName = "prop2a")]
    public string Prop2A;
    
    [JsonProperty(PropertyName = "prop3a")]
    public string Prop3A;
}

The problem is that the json string is now invalid string because the properties are serialized on different levels:

// invalid JSON
{ MyAggregatedPropsA: { prop1a: "", prop2a: "", prop3a: ""}, MyAggregatedPropsB: { prop1b: "", prop2b: "", prop3b: "" } }

Is it possible to get a JSON like the first, using the second class structure?


Solution

  • var obj = new { x = new { a = 1, b = 2 }, y = new { c = 3, d = 4 } };
    
    Func<JToken, IEnumerable<JProperty>> flatten = null;
    
    flatten = token => token.Concat(token.SelectMany(t => t.Children().SelectMany(y => flatten(y))))
                        .OfType<JProperty>()
                        .Where(p => p.Value is JValue || p.Value is JArray);
    
    
    var dict = flatten(JToken.FromObject(obj))
               .ToDictionary(p => p.Name, p => p.Value);
    
    
    var json = JsonConvert.SerializeObject(dict);