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

时间:2018-10-05 15:02:32

标签: c# json.net json-deserialization

我一定是在犯一个愚蠢的错误。当我跑步时:

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时,它可以进行序列化和反序列化。我想念什么?预先感谢。

1 个答案:

答案 0 :(得分:1)

尝试以下操作:

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

$表示元数据。序列化器设置使该值被视为属性。