0

我正在尝试序列化这个模型

public class Rootobject
{
    public Los los { get; set; }
    public int Id { get; set; }
}



      public class Los
        { 
[JsonConverter(typeof(DictionaryToJsonObjectConverter))]
            public Dictionary<DateTime, List<Item>> items { get; set; }
        }


public class Item
{
    public string currency { get; set; }
    public int guests { get; set; }
    public int[] price { get; set; }
}

我得到了这个

{
    "los": {
        "items": {
            "2020-01-10T00:00:00+01:00": [
                {
                    "currency": "EUR",
                    "guests": 1,
                    "price": [
                        443
                    ]
                }
            ],
            "2020-01-11T00:00:00+01:00": [
                {
                    "currency": "EUR",
                    "guests": 1,
                    "price": [
                        500
                    ]
                }
            ]
        }
    },
    "Id": 1
}

我想得到这个回应

{
    "los": {
            "2020-01-10T00:00:00+01:00": [
                {
                    "currency": "EUR",
                    "guests": 1,
                    "price": [
                        443
                    ]
                }
            ],
            "2020-01-11T00:00:00+01:00": [
                {
                    "currency": "EUR",
                    "guests": 1,
                    "price": [
                        500
                    ]
                }
            ]
    },
    "Id": 1}

我想使用属性来实现这一点,但我不知道如何。

我尝试编写我的自定义 json 转换器,但这并没有做太多

 public class DictionaryToJsonObjectConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(IDictionary<DateTime, List<Item>>).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteRawValue(JsonConvert.SerializeObject(value, Formatting.Indented));
        }
    }
4

1 回答 1

1

您的代码中的问题是您填充字典的方式。您当前的班级结构是:

RootObject
|
|
|--los (with json proerty set to display)
    |
    |
    |--- items dictionary

你需要的是这样的:

RootObject
|
|
|-- items dictionary los (either rename the property name to los or use JsonProperty to use los)

因此,为了获得所需的结果,请删除类 Los 并将以下行直接移动到 RootObject 下:

public Dictionary<DateTime, List<Item>> items { get; set; }

并将项目重命名为 los。

因此,在更改之后,您的 Rootobject 对象如下所示:

public class Rootobject
{
    // public Los los { get; set; }
    // I don't think you need this converter unless you have special logic   
    [JsonConverter(typeof(DictionaryToJsonObjectConverter))]
    public Dictionary<DateTime, List<Item>> los { get; set; }
    public int Id { get; set; }
}
于 2020-01-10T14:32:46.383 回答