I'm getting an error when I try to deserialize a JSON string:
Cannot deserialize the current JSON array (eg [1,2,3]) ...
vb.net code:
Public Class DATA
Public Property CPU As String
End Class
Dim data As DATA = JsonConvert.DeserializeObject(Of DATA)(File.ReadAllText("laptop.json"))
TextBox25.Text = DATA.CPU
The JSON file:
[
{
"spec": "CPU";
"value": "Intel Core i3-4005U"
};
{
"spec": "Speed";
"value": "1.7 GHz"
};
{
"spec": "Cache";
"value": "3MB"
};
{
"spec": "RAM";
"value": "4GB"
};
{
"spec": "Warranty Period";
"value": "1 Year"
}
]
How can I fix this error?
There are three problems here.
First, the JSON as you have shown it is invalid. Properties within JSON objects and values within JSON arrays must be separated by commas ( ,
), not semicolons ( ;
). See JSON.org .
Second, your JSON represents an array (or list) of items, but you are trying to deserialize into a single class. You need to deserialize into a list like this:
Dim json As String = File.ReadAllText("laptop.json")
Dim list As List(Of DATA) = JsonConvert.DeserializeObject(Of List(Of DATA))(json)
Third, the property names in the DATA
class you are using do not match the JSON property names of the objects in the array. The class should be defined like this instead:
Class DATA
Public Property spec As String
Public Property value As String
End Class
Fiddle: https://dotnetfiddle.net/0aI2C3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.