Harshal
Harshal

Reputation: 1614

Unable to convert string to JSON object

Below is Json string

{
  "Resources": {
    "Resource": [
      {
        "ResourceId": "D513E96F-EA6C-E511-8133-000D3A0044F4",
        "MSPSLogin": "richa.dinesh.parkar",
        "Email": "[email protected]"
      },
      {
        "ResourceId": "D513E96F-EA6C-E511-8133-000D3A0044F4",
        "MSPSLogin": "harshal.arun.vadnere",
        "Email ": "[email protected]"
      }
    ]
  },
    "CreatedOn":"2016-07-18T12:51:14.23Z",                         
    "CreatedByApp":"AD"                           
}

My class in Models:

public class Resource   
{
    public string ResourceId { get; set; }
    public string MSPSLogin { get; set; }
    public string Email { get; set; }

}

public class Resources
{
    public IList<Resource> Resource { get; set; }
}

public class Example
{
    public Resources Resources { get; set; }
    public DateTime CreatedOn { get; set; }
    public string CreatedByApp { get; set; }
}

I use Json.Net, I want to convert string below to Json Object.

Example example = JsonConvert.DeserializeObject<Example>(jsonstr);

But it error:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[myWizard_MSPS_integration.Example]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

Upvotes: 0

Views: 675

Answers (3)

Yanga
Yanga

Reputation: 3012

Try with this class model:

public class Resource
{
    public string ResourceId { get; set; }
    public string MSPSLogin { get; set; }
    public string Email { get; set; }
}

public class Resources
{
    public List<Resource> Resource { get; set; }
}

public class Example
{
    public Resources Resources { get; set; }
    public string CreatedOn { get; set; }
    public string CreatedByApp { get; set; }
}

Replace

    public IList<Resource> Resource { get; set; }

With

    public List<Resource> Resource { get; set; }

Upvotes: 0

Botond Botos
Botond Botos

Reputation: 1242

Just change the type of Resources property to IEnumerable<Resource>

Upvotes: 3

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30225

Try changing IList<Resource> to IEnumerable<Resource> or Resource[], I think Json.Net cannot initialize IList. Not supported feature.

Upvotes: 3

Related Questions