0

I have the following class which is populated after de-serializing a JSON string:

public class Doors
{
    public List<Door> doors { get; set; }
}

public class Door
{
    public int id { get; set; }
    public string name { get; set; }
    public bool elevator { get; set; }
}

JSON string:

var result = JsonConvert.DeserializeObject<Doors>(response.Content);
// "{\"doors\":[{\"id\":1,\"name\":\"Main Door\",\"elevator\":false},{\"id\":2,\"name\":\"Back Door\",\"elevator\":false}]}"

The data maps to my class fine, I'm then trying to pass the class data to another class:

public class WS4APIResult
{   
    public List<Door> doors { get; set; } = new List<Door>();      
}

public class Door
{
    public int id { get; set; }
    public string name { get; set; }
    public bool elevator { get; set; }
}

return new WS4APIResult() {         
    doors = result.doors
}

With the following error: any ideas please?

Cannot implicitly convert type 'System.Collections.Generic.List<WS4PortalApi.Models.Door>' to 'System.Collections.Generic.List<WS4PortalApi.Domain.Door>'

1
  • 2
    You can't cast an object to another type just because they have the same property names. Write a "copy" method than copies ease property or use a 3rd party library like Automapper. Commented Apr 20, 2020 at 12:57

2 Answers 2

2

The two c#-Files refer to different classes if you type Door. You need to implement a conversion between WS4PortalApi.Models.Door and WS4PortalApi.Domain.Door.

Like:

public static WS4PortalApi.Domain.Door DoorConvert(WS4PortalApi.Models.Door door)

then you can use linq to generate a new List

doors = result.doors
    .Select(d => DoorConvert(d))
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

You have to map the properties of your domain object to those of the model. I normally create a method for this like:

var doors = new List<Model.Door>();
foreach(door in result.doors)
{
     var doorModel = new Model.Door
     {
         id = door.id,
         name = door.name,
         elevator = door.elevator
     };
     doors.Add(doorModel);
}
return doors;

Or you can use a library like automapper.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.