如何序列化\反序列化属性名称依赖于数据的属性

时间:2011-02-22 15:03:37

标签: c# .net json serialization json.net

我正在尝试将以下json(见下文)反序列化(使用newtonsoft json序列化程序),问题是名为“2010-12”的变量,它显然取决于返回的数据 - 它代表一个月和下一个月份价值将变为“2010-01”。

关于我如何处理以下课程的任何想法?

[JsonObject(MemberSerialization.OptIn)]
public class Crimes
{
   [JsonProperty()]
   public Month Month { get; set; }
}

示例JSON实例:

{
    "commentary": null,
    "crimes": {
        "2010-12": {
            "anti-social-behaviour": {
                "crime_rate": "0.46",
                "crime_level": "average",
                "total_crimes": 74
            },
            "other-crime": {
                "crime_rate": "0.35",
                "crime_level": "average",
                "total_crimes": 56
            },
            "all-crime": {
                "crime_rate": "1.12",
                "crime_level": "average",
                "total_crimes": 180
            },
            "robbery": {
                "crime_rate": "0.02",
                "crime_level": "above_average",
                "total_crimes": 3
            },
            "burglary": {
                "crime_rate": "0.14",
                "crime_level": "above_average",
                "total_crimes": 22
            },
            "vehicle-crime": {
                "crime_rate": "0.04",
                "crime_level": "average",
                "total_crimes": 7
            },
            "violent-crime": {
                "crime_rate": "0.11",
                "crime_level": "average",
                "total_crimes": 18
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我不熟悉Newtonsoft的反序列化程序,但一般来说我认为要做的事情是将crime属性反序列化为带有字符串或DateTime键的字典。对不起,我无法告诉你在牛顿软件中究竟该如何做到这一点,但试着去研究它。