Reputation: 45
I have the following string,
[{ "AnimalName" : "Gatto", "Year" : 5.0 }, { "AnimalName" : "Gatto", "Year" : 6.0 }]
I want to Deserialize this string using the class Animali
public class Animali
{
public string AnimalName { get; set; }
public double Year { get; set; }
}
I use the following code,
Animali json = JsonConvert.DeserializeObject<Animali>(string);
My problem is that having two separate element, I receive the error;
Newtonsoft.Json.JsonReaderException: 'Additional text encountered after finished reading JSON content: ,. Path '', line 1, position 40.'
What is the correct way to deserialize the string? Any suggestion?
P.S. Using one elemente like [{ "AnimalName" : "Gatto", "Year" : 5.0 }]
the code works correctly.
Upvotes: 0
Views: 99
Reputation: 9771
Try to parse your json string into JToken.
Cast your JToken to List.
Here I created a console app for your demonstration purpose.
class Program
{
static void Main(string[] args)
{
string json = @"[{ 'AnimalName' : 'Gatto', 'Year' : 5.0 }, { 'AnimalName' : 'Gatto', 'Year' : 6.0 }]";
JToken jToken = JToken.Parse(json); //Point No. 1
List<Animali> animalis = jToken.ToObject<List<Animali>>(); //Point No. 2
foreach (Animali animali in animalis) //Print result
{
Console.WriteLine("AnimalName: " + animali.AnimalName + "\t Year: " + animali.Year);
}
Console.ReadLine();
}
}
Output:
Upvotes: 0
Reputation: 81543
As pointed out, your json is an array, and you need to deserialize it as such
var results = JsonConvert.DeserializeObject<List<Animali>>(string);
Example from the json site
Upvotes: 2