【问题标题】:Azure JSON Response Deserialization C#Azure JSON 响应反序列化 C#
【发布时间】:2020-01-30 03:06:47
【问题描述】:

我的 JSON 响应如下所示,

[
 {
  "faceRectangle": {
     "top": 214,
     "left": 472,
     "width": 450,
     "height": 450
  },
  "faceAttributes": {
     "age": 19.0,
     "emotion": {
        "anger": 0.0,
        "contempt": 0.0,
        "disgust": 0.0,
        "fear": 0.0,
        "happiness": 0.0,
        "neutral": 0.996,
        "sadness": 0.003,
        "surprise": 0.001
     }
   }
 }
]

我的 C# 类如下:

public class Output
{
    public List<FaceRectangle> FaceRectangles { get; set; }
    public List<FaceAttribute> faceAttributes { get; set; }
}
public class FaceAttribute
{
    public List<Emotion> Emotions { get; set; }
    public int age { get; set; }
}
public class Emotion { 
    public float anger { get; set; }
    public float contempt { get; set; }
    public float disgust { get; set; }
    public float fear { get; set; }
    public float happiness { get; set; }
    public float neutral { get; set; }
    public float sadness { get; set; }
    public float surprise { get; set; }
}
public class FaceRectangle
{
    public int top { get; set; }
    public int left { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}

但是,当我尝试反序列化上述响应时,我收到以下错误。 错误代码显示为“不支持数组的反序列化” enter image description here

谁能帮我解决这个问题? 谢谢!

【问题讨论】:

  • 你能记录 format.GetType() 吗?

标签: c# json azure deserialization


【解决方案1】:

尝试使用从json2csharp 创建的这些类:

public class FaceRectangle
{
    public int Top { get; set; }
    public int Left { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
}

public class Emotion
{
    public double Anger { get; set; }
    public double Contempt { get; set; }
    public double Disgust { get; set; }
    public double Fear { get; set; }
    public double Happiness { get; set; }
    public double Neutral { get; set; }
    public double Sadness { get; set; }
    public double Surprise { get; set; }
}

public class FaceAttributes
{
    public double Age { get; set; }
    public Emotion Emotion { get; set; }
}

public class RootObject
{
    public FaceRectangle FaceRectangle { get; set; }
    public FaceAttributes FaceAttributes { get; set; }
}

然后您可以使用 Newtonsoft.Json NuGet 包将您的 JSON 数组响应反序列化为 List&lt;RootObject:

using Newtonsoft.Json;

...

var json = @"[{""faceRectangle"": {""top"": 214,""left"": 472,""width"": 450,""height"": 450},""faceAttributes"": {""age"": 19.0,""emotion"": {""anger"": 0.0,""contempt"": 0.0,""disgust"": 0.0,""fear"": 0.0,""happiness"": 0.0,""neutral"": 0.996,""sadness"": 0.003,""surprise"": 0.001}}}]";

var deserializedJson = JsonConvert.DeserializeObject<List<RootObject>>(json);

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多