反序列化序列化字符串时出现 C# Newtonsoft JsonSerializationException

C# Newtonsoft JsonSerializationException when deserializing a serialized string

我一定是犯了一个愚蠢的错误。当我 运行:

JsonResponse testREsponse = new JsonResponse
            {
                StartTimeUtc = 1,
                EndTimeUtc = 1,
                TimeResolutionInMilliseconds = 60000,
                Results = new JsonResults
                {
                    Type = "hello",
                    Values = new List<EvaluatedResult>()
                }
            };
            string convertTest = JsonConvert.SerializeObject(testREsponse);
            Console.WriteLine("HRMM " + convertTest);
            JsonResponse jsonResponse = JsonConvert.DeserializeObject<JsonResponse>(convertTest);

我得到一个

Unhandled Exception: Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JarvisReader.JsonResults' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

在尝试反序列化一个字符串时,我序列化了上面的行。它表示“路径 'results.$values',第 1 行,位置 71。”这将是结果括号。

对象:

class JsonResponse
{
    [JsonProperty("startTimeUtc")]
    public long StartTimeUtc { get; set; }
    [JsonProperty("endTimeUtc")]
    public long EndTimeUtc { get; set; }
    [JsonProperty("results")]
    public JsonResults Results { get; set; }
    [JsonProperty("timeResolutionInMilliseconds")]
    public int TimeResolutionInMilliseconds { get; set; }
}

class JsonResults
{
    [JsonProperty("$type")]
    public string Type { get; set; }

    [JsonProperty("$values")]
    public List<EvaluatedResult> Values { get; set; }
}

class EvaluatedResult
{
    [JsonProperty("dimensionList")]
    public DimensionList dimensionList { get; set; }
    [JsonProperty("evaluatedResult")]
    public decimal evaluatedResult { get; set; }
    [JsonProperty("seriesValues")]
    public List<Decimal> seriesValues { get; set; }
}

class DimensionList
{
    [JsonProperty("$type")]
    public string type { get; set; }

    [JsonProperty("$values")]
    public List<Dimension> values;
}

class Dimension
{
    [JsonProperty("key")]
    public string key { get; set; }
    [JsonProperty("value")]
    public string value { get; set; }
}

我将我的 testREsponse 浓缩为几乎是空的。看起来它序列化得很好。

{"startTimeUtc":1,"endTimeUtc":1,"results":{"$type":"hello","$values":[]},"timeResolutionInMilliseconds":60000}

当我从构造中删除 JsonResults 时,它可以很好地序列化和反序列化。我错过了什么?提前致谢。

尝试以下操作:

JsonConvert.DeserializeObject<JsonResponse>(convertTest, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore });

$ 表示元数据。序列化程序设置使该值像 属性.

一样处理