user9933478
user9933478

Reputation:

How to specific C# property to Json object in ASP.NET MVC?

++ 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"
    }

Upvotes: 1

Views: 1201

Answers (4)

Amir Molaei
Amir Molaei

Reputation: 3810

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();
    }

Upvotes: 4

Leke Okewale
Leke Okewale

Reputation: 15

Annotate the field you want to exclude with[JsonIgnore]

Upvotes: 0

Harsimran Dhami
Harsimran Dhami

Reputation: 31

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

Upvotes: 2

Michal Ja
Michal Ja

Reputation: 252

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

Upvotes: 0

Related Questions