-2

I am writing a web api using my existing model classes and model services which are being used by many other applications too which needs the model to be fully exposed in serialization. Can I use the same model object for web api and expose only few fields.

I have tried using JsonContractResolver, but it fails to serialize child properties in a nested class.

 /*Model class*/
  public class A
  {
    public int A1 { get; set; }
    public DateTime A2 { get; set; }
    public List<B> A3 { get; set; }
  }
  public class B
  {
    public string B1 { get; set; }
    public string B2 { get; set; }
    public string B3 { get; set; }
  }
        

Expected output: When a web app method gets the members of class A, it should return the following JSON:

{"A1":1,"A2":"2017-02-10","A3":[{"B1":"test1","B2":"test2","B3":"test3"}]}

When the web API gets the member of class A, it should return:

{"A1":1,"A3":[{"B1":"test1"}]}

How can I adjust my code to achieve this result?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Jofy Baby
  • 122
  • 8
  • 2
    _"use the same model object for web api and expose only few fields"_ - use viewmodels, use anonymous types or [use a custom serializer per application or endpoint](http://stackoverflow.com/questions/25157511/newtonsoft-add-jsonignore-at-runtime). What did your research show? – CodeCaster Feb 10 '17 at 16:18

1 Answers1

0

Each domain should have its own models/classes. The web app should have a model that exposes all of the fields and the web api should have a model that exposes only part of the field.

namespace X.WebApp.Models {

    public class A {
        public int A1 { get; set; }
            public DateTime A2 { get; set; }
            public List<B> A3 { get; set; }
    }

    public class B {
        public string B1 { get; set; }
            public string B2 { get; set; }
            public string B3 { get; set; }
    }
}

namespace X.WebApi.Models {

    public class A {
        public int A1 { get; set; }
            public List<B> A3 { get; set; }
    }

    public class B {
        public string B1 { get; set; }
    }
}

These models could be built from a more general models namespace

namespace X.Common.Models {

    public class A {
        public int A1 { get; set; }
            public DateTime A2 { get; set; }
            public List<B> A3 { get; set; }
        // More fields...
    }

    public class B {
        public string B1 { get; set; }
            public string B2 { get; set; }
            public string B3 { get; set; }
        // More fields...
    }
}
areller
  • 4,800
  • 9
  • 29
  • 57