Json反序列化报错:无法将JSON对象转为List<VehicleGO>求助
Hey there, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
Your JSON data is structured as a top-level object that contains an array (veiculo), but you're trying to deserialize it directly into a List<VehicleGO> which expects a top-level JSON array. That's why Newtonsoft.Json is throwing the mismatch error—it can't map an object to a collection type.
Here's your JSON structure for clarity:
{ "veiculo": [ { "categoria": "B", "placa": "NLI2892" }, { "categoria": "A", "placa": "OML8712" }, { "categoria": "B", "placa": "PQU1492" }, { "categoria": "B", "placa": "JIC1381" }, { "categoria": "A", "placa": "ONB1093" } ] }
Solution 1: Create a Root Object Class (Recommended)
This is the cleanest, most maintainable approach for strong-type .NET development. We'll define a class that matches the top-level JSON object structure:
public class VehicleRoot { [JsonProperty(PropertyName = "veiculo")] public List<VehicleGO> Vehicles { get; set; } }
Then update your deserialization code to target this root class:
var vehicleRoot = JsonConvert.DeserializeObject<VehicleRoot>(json); var vehicles = vehicleRoot.Vehicles; // This gives you the list of VehicleGO objects
Solution 2: Parse the Array Directly (Quick Fix)
If you don't want to add a new class, you can use JObject to navigate directly to the veiculo array and deserialize it:
using Newtonsoft.Json.Linq; // Make sure you have this using directive var jsonObj = JObject.Parse(json); var vehicles = jsonObj["veiculo"].ToObject<List<VehicleGO>>();
Which Solution to Choose?
- Use Solution 1 if this JSON structure is something you'll work with regularly—it keeps your code type-safe and easy to extend.
- Use Solution 2 for one-off or quick scenarios where adding a new class feels unnecessary.
内容的提问来源于stack exchange,提问作者gregoryp

