Lea*_*dro 3 .net c# asp.net-mvc json json.net
我有一个JsonResult从MVC方法返回的对象,但我需要在发送之前从中删除一个元素.
更新:
我试图在没有映射的情况下完成它,因为对象庞大而且非常复杂.
我怎样才能做到这一点?
例如:
public class MyClass {
public string PropertyToExpose {get; set;}
public string PropertyToNOTExpose {get; set;}
public string Otherthings {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
和
JsonResult result = new JsonResult();
result = Json(myObject, JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)
然后从结果中删除 PropertyToNOTExpose.
真实代码的更新:
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个新对象,不包括您不希望在结果中发送的属性...
var anonymousObj = new {
myObject.PropertyToExpose,
myObject.Otherthings
};
JsonResult result = Json(anonymousObj, JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)
另一个选项可能是将对象转换为Newtonsoft.Json.Linq.JObject并使用JObject删除该属性.Remove方法(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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1886 次 |
| 最近记录: |