0

I have web api controller where I try to do something like this:

public IHttpActionResult Get()
{

    var Rooms = db.Rooms.Select(r => new {
        Id = r.Id,
        Name = r.Name,
        ChairNum = r.СhairNum,
        Requests = r.Requests.ToList()
    }).ToList();

   return Ok(new { results = Rooms });

}

In Model I have this:

public partial class Room
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Room()
    {
        this.Requests = new HashSet<Request>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int СhairNum { get; set; }
    public bool IsProjector { get; set; }
    public bool IsBoard { get; set; }
    public string Description { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Request> Requests { get; set; }
}

I tried to pass this data in service. But I have serialization error, when I call http://localhost:99999/api/Rest.

<ExceptionMessage>
The "ObjectContent`1" type could not serialize the response text for the content type "application / json; charset = utf-8".
</ ExceptionMessage>

What is the best way to pass the data like in model into json?

ekad
  • 14,436
  • 26
  • 44
  • 46
tmf
  • 33
  • 8

1 Answers1

1

It helped to put in WebApiConfig:

  var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    config.Formatters.Remove(config.Formatters.XmlFormatter);
tmf
  • 33
  • 8