skip to Main Content

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);

2

Answers


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

    [JsonObject]
    public class Agents : IEnumerable<Agent>
    {
        ...
    }
    
    Login or Signup to reply.
  2. Please check following points:

    1. Make sure that Agents class has same keys as defined in json. It should be similar to below class

       public class Agents
       {
           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; }
       }
      
    2. Also your json has data for multiple agent id, try below line to convert:

       List<Agents> AgentsData = new JavaScriptSerializer().Deserialize<List<Agents>>(responseString);
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search