Search code examples
c#jsonserializationdeserializationjson-deserialization

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:

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>
    {
        ...
    }