Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'myclass'

I am trying to deserialize a javascript kind of JSON

"{\n  \"resultSet1\": [\n    {\n      \"AgentID\": 13173,\n      \"FirstName\": \"Drilon\",\n      \"SG_ID\": 14336,\n      \"LoginName\": \"UI813926\",\n      \"SG_Description\": \"LKC Bauhotline\",\n      \"SG_Name\": \"Y_BAU__FO\",\n      \"EnterpriseName\": \"LKC_Abdullahu_Drilon\",\n      \"LastName\": \"Abdullahu\"\n    },\n    {\n      \"AgentID\": 14432,\n      \"FirstName\": \"Pinar\",\n      \"SG_ID\": 14336,\n      \"LoginName\": \"UI938008\",\n      \"SG_Description\": \"LKC Bauhotline\",\n      \"SG_Name\": \"Y_BAU__FO\",\n      \"EnterpriseName\": \"LKC_Ali_Pinar\",\n      \"LastName\": \"Ali\"\n    },  ]\n}"

Agents and Agent classes are

public class Agent
{
    public int AgentID { get; set; }
    public string FirstName { get; set; }
    public int SG_ID { get; set; }
    public string LoginName { get; set; }
    public string SG_Description { get; set; }
    public string SG_Name { get; set; }
    public string EnterpriseName { get; set; }
    public string LastName { get; set; }
}

public class Agents : IEnumerable<Agent>
{
    public List<Agent> resultSet1 { get; set; }

    public IEnumerator<Agent> GetEnumerator()
    {
        return ((IEnumerable<Agent>)resultSet1).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable)resultSet1).GetEnumerator();
    }
}

with Newtonsoft.json like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Agents result = JsonConvert.DeserializeObject<Agents>(responseString);

And getting the following error:

Newtonsoft.Json.JsonSerializationException: ‘Cannot deserialize the current JSON object (e.g. {"name": "value"}) into type ‘myclass’ because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

It is deserializing fine with the nancy.json library.

Agents AgentsData = new JavaScriptSerializer().Deserialize<Agents>(responseString);

>Solution :

Agents implements IEnumerable<>, mark it with JsonObjectAttribute to enforce deserialization as/from object:

[JsonObject]
public class Agents : IEnumerable<Agent>
{
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading