mems
mems

Reputation: 45

Deserialize two element string in JSON

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

Answers (2)

er-sho
er-sho

Reputation: 9771

  1. Try to parse your json string into JToken.

  2. 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:

enter image description here

Upvotes: 0

TheGeneral
TheGeneral

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

Deserialize a Collection

Upvotes: 2

Related Questions