Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element from JsonResult in C#

I've a JsonResult object to return from a MVC method, but I need to remove one element from it before send it.

UPDATE:
I'm trying to do it without mapping it because the object is huge and very complex.

How can I achieve this?

For eg.:

public class MyClass {

   public string PropertyToExpose {get; set;}
   public string PropertyToNOTExpose {get; set;}
   public string Otherthings {get; set;}

}

and

JsonResult result = new JsonResult();
result = Json(myObject, JsonRequestBehavior.AllowGet);

and then REMOVE PropertyToNOTExpose from the result.

UPDATE from real code:

public JsonResult GetTransaction(string id)
{    
    //FILL UP transaction Object

    JsonResult resultado = new JsonResult();

    if (CONDITION USER HAS NOT ROLE) {
        var jObject = JObject.FromObject(transaction);
        jObject.Remove("ValidatorTransactionId");
        jObject.Remove("Validator");
        jObject.Remove("WebSvcMethod");
        resultado = Json(jObject, JsonRequestBehavior.AllowGet);
    } else {
        //etc.
    }
    return resultado;
}
like image 431
Leandro Bardelli Avatar asked May 25 '26 11:05

Leandro Bardelli


1 Answers

You can create a new object, excluding the properties you don't want sent in the result...

var anonymousObj = new {
   myObject.PropertyToExpose,
   myObject.Otherthings
};
JsonResult result = Json(anonymousObj, JsonRequestBehavior.AllowGet);

Another options could be to convert the object to a Newtonsoft.Json.Linq.JObject and remove the property using JObject.Remove Method (String)

var jObject = JObject.FromObject(myObject);
jObject.Remove("PropertyToNOTExpose");
var json = jObject.ToString(); // Returns the indented JSON for this token.
var result = Content(json,"application/json");
like image 60
Nkosi Avatar answered May 28 '26 00:05

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!