0

I have an ASP MVC Web Api project that outputs json using json.net. I have for example the following models:

public class ModelA
{
    public int Id {get;set;}
    public string Name {get;set;}

    [JsonIgnore]
    public int TypeModelId {get;set;}
    public virtual TypeModel TypeModel {get;set;}
}

public class TypeModel
{
    [JsonIgnore]
    public int Id {get;set;}

    public string Name {get;set;}

    [JsonIgnore]
    public virtual IList<ModelA> ModelAs {get;set;}
}

When I serialize a ModelA the output will be something like this:

[
  {
    "Id": 1,
    "Name": "test",
    "TypeModel": {
      "Name": "testtype1"
    }
  }
]

Is it possible using json.net to have an output like this..

[
  {
    "Id": 1,
    "Name": "test",
    "TypeModel": "testtype1"
  }
]

..or do I have to copy the contents of ModelA to a new class which stores the TypeModel relation as string instead of reference? Maybe there are better solutions?

2 Answers 2

1

As you say the only way to do this is with a DTO. This is because, as you indicated, the type of TypeModel is a class TypeModel and not a string. If you are using Linq you could also just use an anonymous type in the following way.

return db.ModelAs.Single(x=>x.Id == id).Select(x=> new{
    x.Id,
    x.Name,
    TypeModel = x.TypeModel.Name
});
Sign up to request clarification or add additional context in comments.

2 Comments

Too bad a DTO is the only way, but your Linq solution is better than creating additional classes. Another solution I found is to json-ignore the TypeModel class, and creating a NotMapped get property for TypeModel.Name, but unfortunately that will get the datamodel classes a bit messy.
Yes I have recently had the same issue with Annotating my classes when trying to serialise object with Web Api, I've found using DTOs to be the best way (better than anonymous types) as you get better consistency. Good luck!
0

Actually this is not true, json.net can handle loop reference handling, dto is an old method, still good, but you can enable in the serializer the option to handle loopreferences as long as it is mvc5 and maybe also mvc4. More details here: https://stackoverflow.com/a/23044770/1345207

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.