C# 在C中从JsonResult中删除一个元素#

C# 在C中从JsonResult中删除一个元素#,c#,.net,json,asp.net-mvc,json.net,C#,.net,Json,Asp.net Mvc,Json.net,我有一个要从MVC方法返回的JsonResult对象,但我需要在发送它之前从中删除一个元素 更新: 我试图在不映射它的情况下完成它,因为对象是巨大且非常复杂的 我怎样才能做到这一点 例如: public class MyClass { public string PropertyToExpose {get; set;} public string PropertyToNOTExpose {get; set;} public string Otherthings {get; s

我有一个要从MVC方法返回的
JsonResult
对象,但我需要在发送它之前从中删除一个元素

更新:
我试图在不映射它的情况下完成它,因为对象是巨大且非常复杂的

我怎样才能做到这一点

例如:

public class MyClass {

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

}

然后从结果中删除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;
}

您可以创建一个新对象,不包括不希望在结果中发送的属性

var anonymousObj = new {
   myObject.PropertyToExpose,
   myObject.Otherthings
};
JsonResult result = Json(anonymousObj, JsonRequestBehavior.AllowGet);
另一个选项可以是将对象转换为,并使用


您可以尝试在属性上使用
[ScriptIgnore]
属性。这将导致
JavaScriptSerializer
忽略它。然而,这意味着在反序列化时它也将被忽略。我不确定这对你的处境是否是个问题

public class myClass 
{
   public string PropertyToExpose {get; set;}
   [ScriptIgnore]
   public string PropertyToNOTExpose {get; set;}
   public string Otherthings {get; set;}
}

另一个想法是将对象序列化为
JObject
,并在将其传递给result之前删除该属性。使用原始myObject示例显示新结构的示例。我相信这会很简单fix@LeandroTupone我发现了问题并更新了答案。在
JObject
上调用
ToString
,以获取要在结果中发送的Json。您可以在客户端将字符串解析为Json!谢谢。最后,我更改为ActionResult,然后返回内容(json,“应用程序/json”);谢谢,我不知道,所以即使不回答我,我也认为这是一个很好的回答。实际上,如果用户没有rol,我必须过滤一些元素,所以我有一点条件逻辑。如果用户有rol,我将全部显示,如果没有,我将对其进行过滤
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");
public class myClass 
{
   public string PropertyToExpose {get; set;}
   [ScriptIgnore]
   public string PropertyToNOTExpose {get; set;}
   public string Otherthings {get; set;}
}