JSON.NET:如何序列化嵌套集合 [英] JSON.NET: How to Serialize Nested Collections

查看:285
本文介绍了JSON.NET:如何序列化嵌套集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我发疯了...我正在使用Json.net将列表序列化为JSON.我希望这个JSON:

This is driving me nuts... I am serializing a List to JSON using Json.net. I expect this JSON:

{
    "fieldsets": [
        {
            "properties": [
                {
                    "alias": "date",
                    "value": "2014-02-12T00:00:00"
                },
                {
                    "alias": "time",
                    "value": null
                }
            ],
            "alias": "eventDates",
            "disabled": false
        }
    ]
}

但是我得到了:

{
    "fieldsets": [
        {
            "properties": [
                {
                    "values": [
                        {
                            "alias": "date",
                            "value": "2014-07-13T00:00:00"
                        },
                        {
                            "alias": "time",
                            "value": "Registration begins at 8:00 AM; walk begins at 9:00 AM"
                        }
                    ]
                }
            ],
            "alias": "eventDates",
            "disabled": false
        }
    ]
}

我只希望将"values"集合作为一个JSON数组,但是我一辈子都无法弄清楚如何做到这一点.我在属性"对象上有一个称为值"的属性,因此我了解为什么要这样做,但是我只需要直接数组,而不需要JSON对象.

The "values" collection I'd like as just a JSON array, but I can't for the life of me figure out how to get it to do this. I have a property on my "properties" objects called "values", so I understand why it's doing it, but I need just the straight array, not a JSON object.

推荐答案

对于该响应,您需要此类结构

For that response, you need this class structure

public class Property
{
    [JsonProperty("alias")]
    public string Alias { get; set; }

    [JsonProperty("value")]
    public string Value { get; set; }
}

public class Fieldset
{
    [JsonProperty("properties")]
    public Property[] Properties { get; set; }

    [JsonProperty("alias")]
    public string Alias { get; set; }

    [JsonProperty("disabled")]
    public bool Disabled { get; set; }
}

public class Response
{
    [JsonProperty("fieldsets")]
    public Fieldset[] Fieldsets { get; set; }
}

这篇关于JSON.NET:如何序列化嵌套集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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