Reputation: 11608
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;
}
Upvotes: 3
Views: 4112
Reputation: 247571
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");
Upvotes: 7
Reputation: 129827
You could try using the [ScriptIgnore]
attribute on your property. This will cause the JavaScriptSerializer
to ignore it. However, this means that it will be ignored on deserialization as well. I'm not sure whether that is an issue for your situation or not.
public class myClass
{
public string PropertyToExpose {get; set;}
[ScriptIgnore]
public string PropertyToNOTExpose {get; set;}
public string Otherthings {get; set;}
}
Upvotes: 2