I have this data structure:
public class AutoCompleteObject
{
public Predictions[] predictions { get; set; }
public string status { get; set; }
}
public class Predictions
{
public string description { get; set; }
}
and this is the result of my api:
{
"predictions": [
{
"description": "Hoisberg 142, Hamburg, Germany",
"matched_substrings": [
{
"length": 8,
"offset": 0
},
{
"length": 2,
"offset": 9
},
{
"length": 7,
"offset": 13
}
],
"place_id": "ChIJr_7fvYSKsUcRejFkuj1Nr0o",
"reference": "ChIJr_7fvYSKsUcRejFkuj1Nr0o",
"structured_formatting": {
"main_text": "Hoisberg 143",
"main_text_matched_substrings": [
{
"length": 8,
"offset": 0
},
{
"length": 2,
"offset": 9
}
],
"secondary_text": "Hamburg, Germany",
"secondary_text_matched_substrings": [
{
"length": 7,
"offset": 0
}
]
},
}
],
"status": "OK"
}
I am trying to deserialize into my object using this:
ObservableCollection<AutoCompleteObject> res = JsonConvert.DeserializeObject<ObservableCollection<AutoCompleteObject>>(content);
But it fails stating it was unable to put the string into the array. But the result is an array and can contain many elements. What am I missing?
CodePudding user response:
The exception thrown is the following
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.ObjectModel.ObservableCollection`1[AutoCompleteObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
So the exception point to the problem being that it expects an array. If you look at the json example you provided it starts with {
which means it's a json object. To fix it you need to wrap the json object in []
or deserialize to a different class.
For example your json would have to look like this:
[
{
"predictions": [
{
"description": "Hoisberg 142, Hamburg, Germany",
"matched_substrings": [
{
"length": 8,
"offset": 0
},
{
"length": 2,
"offset": 9
},
{
"length": 7,
"offset": 13
}
],
"place_id": "ChIJr_7fvYSKsUcRejFkuj1Nr0o",
"reference": "ChIJr_7fvYSKsUcRejFkuj1Nr0o",
"structured_formatting": {
"main_text": "Hoisberg 143",
"main_text_matched_substrings": [
{
"length": 8,
"offset": 0
},
{
"length": 2,
"offset": 9
}
],
"secondary_text": "Hamburg, Germany",
"secondary_text_matched_substrings": [
{
"length": 7,
"offset": 0
}
]
}
}
],
"status": "OK"
}
]