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

2

4 Answers 4

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();
    }
Sign up to request clarification or add additional context in comments.

5 Comments

Can you tell me about Controller?
The controller is fine and does not need any changes.
Try [ScriptIgnore] from System.Web.Script.Serialization instead of [JsonIgnore] and let me know it's working.
use [ScriptIgnore] instead of [JsonIgnore] It's working. Thank you.
Glad it helped. And since you are using JavaScriptSerializer , [JsonIgnore] wouldn't work for you.
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

2 Comments

I don't understand, I am beginner.
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.
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

Comments

0

Annotate the field you want to exclude with[JsonIgnore]

1 Comment

I already try [JsonIgnore] It's not work. but use [ScriptIgnore] It's work. Answer from above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.