Почему ответ JSON нельзя десериализовать как List <>, даже если это массив? - PullRequest
0 голосов
/ 17 мая 2019

Прежде всего, извините за длинный и, возможно, излишний вопрос. Я признаю, что видел подобный вопрос, но я честно попробовал все решения, но это не решило мои проблемы. Я кодирую с использованием .NET в C #, используя Newtonsoft и RestSharp в качестве своих пакетов Nu-Get, и пытаюсь получить данные из Wordnik API.

Вот как выглядит JSON:

[
  {
    "id": "A5530700-1",
    "partOfSpeech": "interjection",
    "attributionText": "from The American Heritage® Dictionary of the English Language, 5th Edition.",
    "sourceDictionary": "ahd-5",
    "text": "Used to show encouragement or approval to a boy or man.",
    "sequence": "1",
    "score": 0,
    "labels": [],
    "citations": [],
    "word": "attaboy",
    "relatedWords": [],
    "exampleUses": [
      {
        "text": "Attaboy! That's the way to hit a home run!"
      }
    ],
    "textProns": [],
    "notes": [],
    "attributionUrl": "https://ahdictionary.com/",
    "wordnikUrl": "https://www.wordnik.com/words/attaboy"
  },
  {
    "partOfSpeech": "interjection",
    "attributionText": "from Wiktionary, Creative Commons Attribution/Share-Alike License.",
    "sourceDictionary": "wiktionary",
    "text": "Used to show encouragement or approval to a boy or man.",
    "labels": [
      {
        "text": "idiomatic",
        "type": "usage"
      },
      {
        "text": "colloquial",
        "type": "register"
      }
    ],
    "citations": [],
    "word": "attaboy",
    "relatedWords": [],
    "exampleUses": [],
    "textProns": [],
    "notes": [],
    "attributionUrl": "http://creativecommons.org/licenses/by-sa/3.0/",
    "wordnikUrl": "https://www.wordnik.com/words/attaboy"
  }
]

Это проблемная часть моего кода:

        IRestResponse response = client.Execute(request);

        var resultArray = JsonConvert.DeserializeObject<List<ResultsDefinition>>(response.Content);
        string wordDefinition = resultArray[0].Text;

и это мой класс ResultsDefinition:

public class ResultsDefinition
{
    public string ExtendedText { get; set; }
    public string Text { get; set; }
    public string SourceDictionary { get; set; }
    public List<Citation> Citations { get; set; }
    public List<Label> Labels { get; set; }
    public float Score { get; set; }
    public List<ExampleUsage> ExampleUses { get; set; }
    public string AttributionUrl { get; set; }
    public string SeqString { get; set; }
    public string AttributionText { get; set; }
    public List<Related> RelatedWords { get; set; }
    public string Sequence { get; set; }
    public string Word { get; set; }
    public List<Note> Notes { get; set; }
    public List<TextPron> TextProns { get; set; }
    public string PartOfSpeech { get; set; }
}

public class Citation
{
    public string Cite { get; set; }
    public string Source { get; set; }
}

public class Label
{
    public string Text { get; set; }
    public string Type { get; set; }
}

public class ExampleUsage
{
    public string Text { get; set; }
}

public class Related
{
    public string Label1 { get; set; }
    public string RelationshipType { get; set; }
    public string Label2 { get; set; }
    public string Label3 { get; set; }
    public List<string> Words { get; set; }
    public string Gram { get; set; }
    public string Label4 { get; set; }
}

public class Note
{
    public string NoteType { get; set; }
    public List<string> AppliesTo { get; set; }
    public string Value { get; set; }
    public int Pos { get; set; }
}

public class TextPron
{
    public string Raw { get; set; }
    public int Seq { get; set; }
    public string RawType { get; set; }
}

Каждый раз, когда я пытался запустить свой код в VisualStudio, он всегда давал мне исключение Newtonsoft.Json.JsonSerializationException. Насколько я понимаю, это потому, что JSON читается как JsonObject, а не JsonArray.

Я прочитал здесь , что мне нужно поместить inputString в параметр JsonConvert.DeserializeObject, но я уже сделал это правильно (так как я пишу 'response.Content' в моем коде)?

Это точное исключение, которое я получаю:

Newtonsoft.Json.JsonSerializationException: 'Невозможно десериализовать текущий объект JSON (например, {"name": "value"}) в тип' System.Collections.Generic.List`1 [ConsoleAppTest.ResultsDefinition] ', так как тип требует массив JSON (например, [1,2,3]) для правильной десериализации.

У вас есть предложения, чтобы это исправить?

Ответы [ 2 ]

0 голосов
/ 17 мая 2019

Если response.content не строка, попробуйте это:

var responseString = JsonConvert.SerializeObject(response.content);
var resultArray = JsonConvert.DeserializeObject<List<ResultsDefinition>>(responseString );
0 голосов
/ 17 мая 2019

Хорошо работает со мной.

Посмотрите на этот образец.

enter image description here

https://dotnetfiddle.net/tZfHaZ

Чтоэто response.Content тип данных?

Если вы используете двойную кавычку в качестве оболочки, убедитесь, что вы сбрасываете значение атрибута с помощью обратной косой черты \".

Если вы используете одинарную кавычку в качестве оболочки, убедитесь, что вы избегаете значения атрибутас обратной косой чертой \'.

...