Json.NET 在同一级别序列化属性

本文关键字:一级 序列化 属性 NET Json | 更新日期: 2023-09-27 18:30:23

我有一个很长很复杂的JSON要发送到外部Web服务.
JSON 具有同一级别的所有属性:

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;
    
    // [...]
}

生成的 JSON:

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

为了更好地工作,我在逻辑上将类似的属性分成更小的类:

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;
}

问题是 json 字符串现在是无效字符串,因为这些属性在不同的级别上序列化:

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

是否可以使用第二个类结构获得像第一个这样的 JSON?

Json.NET 在同一级别序列化属性

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);