-1

I'm trying to deserialize a response from an API.

[
  {
    "field1": "value a",
    "field2": "value b"
  },
  {
    "field1": "value c",
    "field2": "value d`"
  }
]

And I'm getting an error...

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'myProject.Models.MyDataModelRoot' because the type requires a JSON object to deserialize correctly. To fix this error either change the JSON to a JSON object or change the deserialzed type to an array or a type that implements a collection interface.

I need to make a data model that is representative of the data I'm getting back.

I've tried a couple samples of data models. Most of them need names and I dont have names... I tried a suggestion I read on here for a similar problem, but it did not work for me.

public class MyDataModelRoot : List<DataEntry>
{

}

public class DataEntry
{

  [JsonProperty(ProperyName = "field1"]
  public string Field1 { get; set; }

  [JsonProperty(ProperyName = "field2"]
  public string Field2 { get; set; }

}

HttpClient httpClient = specialHttpClient.GetHttpClient();
HttpClient.AddCredentials(creds)
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiuri)
MyDataModelRoot dataRoot = await.HttpClient.GetAsync<MyDataModelRoot>(request)  
^^^ This is where it errors...

1 Answers1

4

Your MyDataModelRoot class does not seem to serve any purpose, as you got a json array to deserialize and you can deserialize it directly into a List<DataEntry> list or DataEntry[] array.

E.g.:

List<DataEntry> dataEntries = JsonConvert.DeserializeObject<List<DataEntry>>(jsonFromResponse);

That said, if you insist on using the MyDataModelRoot class for whatever reason, you have to post a minimal and complete reproducible code example with your question that reproduces the issue. Because the vanilla Newtonsoft.Json library does not seem to have an issue with the MyDataModelRoot class as presented in the question when using default (de)serialization settings (proof: https://dotnetfiddle.net/67kT8o).

  • Thanks for getting back! I tried yout suggestion. I have to use a special httpclient that does deserialization internally. It looks like there is no way to make a data model that will work.... maybe I have to not use the special http client and remake this with the regular one... I added the code above. – SteveTinkers Jun 12 '23 at 08:37