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?

4
  • What do you mean you have a serialization error? What error? What line of code does it come from? Commented Oct 31, 2017 at 16:40
  • If I delete Requests = r.Requests.ToList() from the example there are no errors Commented Oct 31, 2017 at 16:45
  • You have not addressed my comment. Commented Oct 31, 2017 at 16:46
  • The answers here might be helpful: stackoverflow.com/questions/13959048/… Commented Oct 31, 2017 at 17:04

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

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.