C# - Deserialize a JSON string with two arrays?
I am using C# to retrieve JSON data. The JSON has two arrays, one for rental cars and one for company cars, and then each car has two pieces of data. JSON output is like the follwing
{"companycars":[[VIN,LICENSEPLATE],[VIN,LICENSEPLATE],"rentalcars":[[VIN,LICENSEPLATE],[VIN,LICENSEPLATE]]}
I am using JSON.net and can handle one array to deserialize to a sim开发者_如何学运维ple string Dictionary with something like
Dictionary<string, string> allCars = JsonConvert.DeserializeObject<Dictionary<string, string>>(myCars);
But what is the example for two arrays within the same result? I want to basically end up with two dictionary (string) objects.
Try creating a class to store the result of your de serialised JSON like so:
public class Cars
{
public List<string[]> Companycars { get; set; }
public List<string[]> Rentalcars { get; set; }
public Cars()
{
Rentalcars = new List<string[]>();
Companycars = new List<string[]>();
}
}
string myCars = "{\"companycars\":[[\"VIN\",\"LICENSEPLATE\"],[\"VIN\",\"LICENSEPLATE\"]],\"rentalcars\":[[\"VIN\",\"LICENSEPLATE\"],[\"VIN\",\"LICENSEPLATE\"]]}";
Cars allCars = JsonConvert.DeserializeObject<Cars>(myCars);
Hope this helps.
Edit:
If you don't need to pass the object around you could store the result into an anonymous type:
var allCars = new
{
CompanyCars = new List<string[]>(),
RentalCars = new List<string[]>()
};
string myCars = "{\"companycars\":[[\"VIN\",\"LICENSEPLATE\"],[\"VIN\",\"LICENSEPLATE\"]],\"rentalcars\":[[\"VIN\",\"LICENSEPLATE\"],[\"VIN\",\"LICENSEPLATE\"]]}";
allCars = JsonConvert.DeserializeAnonymousType(myCars, allCars);
精彩评论