1
++ Model

    public class Product{
        public int ProductId { get; set; }
        public string ProductName { get; set; }

        public DataTable dt = new DataTable();
        public Category Category = new Category();
    }

++Controller

    public JsonResult Index(){
        Product dto = new Product();
        dto.ProductId = 1;
        dto.ProductName = "Coca Cola";
        return Json(dto, JsonRequestBehavior.AllowGet);
    }

How to specific Json object, I mean need only ProductId, ProductName and other no need to Json object.

++Want

    {
        "ProductId": 1,
        "ProductName": "Coca Cola"
    }

  • 1
    One possible way is to return anonymous object like `return Json(new { ProductId = dto.ProductId, ... });` – Aleks Andreev Apr 04 '19 at 11:04
  • Possible duplicate of [Only serialize some specific properties of a class?](https://stackoverflow.com/questions/13658580/only-serialize-some-specific-properties-of-a-class) – krillgar Apr 04 '19 at 11:04

4 Answers4

4

You can use [ScriptIgnore] attribute from System.Web.Script.Serialization on every property that you want to exclude from the object when serializing or deserializing:

  using System.Web.Script.Serialization;

  public class Product{
        public int ProductId { get; set; }
        public string ProductName { get; set; }

        [ScriptIgnore]
        public DataTable dt = new DataTable();
        [ScriptIgnore]
        public Category Category = new Category();
    }
Amir Molaei
  • 3,700
  • 1
  • 17
  • 20
2

In same class, create two functions returning boolean like this:

 public bool ShouldSerializedt()
 {
      return false;
 }

 public bool ShouldSerializeCategory()
 {
      return false;
 }

Function returns boolean. Its name is ShouldSerialize<<PropertyName>> and the return type of boolean controls serialization behavior

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
  • I don't understand, I am beginner. –  Apr 04 '19 at 11:18
  • In the same Product class where you are defining properties like ProductId , ProductName etc. define the functions I mentioned. Check the name of both functions. Name starts with "ShouldSerialize" and end with "dt" or "Category" which are names of properties which shouldn't be serialized. If such function returns false, then corresponding property won't get serialized. – Harsimran Dhami Apr 04 '19 at 12:45
0

Best to use C# serialization mechanism. You may need separate class for the purpose of this "limited" serialization (in case you want these properties serialized in other scenarios) but that should do it. Take a look here: How to exclude property from Json Serialization

Michal Ja
  • 252
  • 3
  • 8
0

Annotate the field you want to exclude with[JsonIgnore]

Leke Okewale
  • 15
  • 1
  • 8
  • I already try [JsonIgnore] It's not work. but use [ScriptIgnore] It's work. Answer from above. –  Apr 04 '19 at 16:24