2

I'm building some small booking app and I'm getting this error all the time.

I solved it with: config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

but now I'm getting answer like this:

{
    "ApartmentId": 1,
    "Building": {
        "BuildingId": 1,
        "Apartments": [
            {
                "ApartmentId": 2,
            }
        ]
    },
}

For class building everything works fine. It's only going "to far" for the apartment. I tried solutions from this topic but it didn't work: https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type#=

Here are my classes:

public class Apartment
{
    public int ApartmentId { get; set; }
    public Building Building { get; set; }
}

public class Building
{
    public int BuildingId { get; set; }
    public List<Apartment> Apartments { get; set; }
}

The question is, what am I missing? How to get rid of listing of apartments for the second time?

Buh Buh
  • 7,281
  • 1
  • 35
  • 59
NiishaO
  • 19
  • 3
  • Could you be more specific what is wrong with your result. If you could remove extra properties, it would be much easier to answer. – andnik Feb 16 '18 at 15:05
  • When i ask for the apartment, I want to get building that it belongs to but not the listing of the apartments in that building. – NiishaO Feb 16 '18 at 15:09
  • 1
    You have an unfortunate typo in `BedroomCount`. (I hope it's a typo. I don't know what type of business you run.) – Buh Buh Feb 16 '18 at 15:14
  • You might want to try a Custom JsonConverter. Not sure. https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm – Buh Buh Feb 16 '18 at 15:33

1 Answers1

0

Since youre using Newtosoft's Json library, you can use the attribute [JsonIgnore]. The property with this attribute won't show up in your json.

You can put it with the Apartments property in your Building class:

public class Building
{
    //All other properties ...

    [JsonIgnore]
    public List<Apartment> Apartments { get; set; }
}

If you want to have different serialising behaviours for the same class, I recommend implementing the DTO classes approach with each class for each data transfer scenario and add attributes as you wish.

Also this document from Microsoft about DTO pattern.

Guilherme Holtz
  • 475
  • 6
  • 18
  • I tried that. But in that case I'm not getting that property listed when i need it in Buildings listing. – NiishaO Feb 16 '18 at 15:15
  • If you want the same class to behave in different ways when serialising, I think you have to implement DTO classes each with its own behaviour designed. – Guilherme Holtz Feb 16 '18 at 15:23
  • This is my first project so I'm trying to solve every possible problem without just running from it. I thought that maybe I made some "stupid" mistake that I'm not seeing but since its not the case ill try with DTO. – NiishaO Feb 16 '18 at 15:44