Json.NET在同一级别上序列化属性 [英] Json.NET serialize property on the same level

查看:49
本文介绍了Json.NET在同一级别上序列化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常长且复杂的JSON,可以发送到外部Web服务.
JSON具有相同级别的所有属性:

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;

    // [...]
}

生成的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;
}

问题在于json字符串现在是无效字符串,因为属性在不同级别上进行了序列化:

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: "" } }

是否可以使用第二个类结构来获取与第一个类似的JSON?

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

谢谢!

推荐答案

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

这篇关于Json.NET在同一级别上序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆