Azure JSON Десериализация ответа C# - PullRequest
3 голосов
/ 30 января 2020

Мой 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; }
}

Однако, когда я пытаюсь десериализовать вышеуказанный ответ Я получаю следующую ошибку. Код ошибки отображается как «Не поддерживается для десериализации массива» введите описание изображения здесь

Может кто-нибудь помочь мне с этим? Спасибо!

1 Ответ

0 голосов
/ 30 января 2020

Попробуйте использовать эти классы, созданные из 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; }
}

Затем вы можете десериализовать свой ответ JSON Array в List<RootObject, используя Newtonsoft. Json NuGet Пакет:

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);
...