如何在JSON序列化期间删除$ id

Saj*_*Ali 32 json.net

我正在使用NewtonSoft.JSON.跑步时

JsonConvert.SerializeObject(myObject)
Run Code Online (Sandbox Code Playgroud)

它正在$id为我的JSON 添加一个值 - 就像这样:

  "$id": "1",
  "BookingId": 0,
  "CompanyId": 0,
  "IsCashBooking": false,
  "PaymentMethod": 0,
  "IsReferral": false,
  "IsReferralPercent": false,
  "ReferralPaymentType": 0,
  "ReferralDues": 0,
  "PassengerId": 0,
  "DepartmentID": 0,
  "CostCenterID": 0,
  "DeadMiles": 0
Run Code Online (Sandbox Code Playgroud)

我们可以$id用一些JsonSerializerSettings或任何其他方法删除它吗?

如果是 - 那么如何......

Eti*_*gné 49

我将此代码添加到我的WebApiConfig寄存器方法中,我在JSON中删除了所有$ id.

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
Run Code Online (Sandbox Code Playgroud)

  • 如果您不需要递归序列化(序列化层次结构),则为有效答案.$ id用于保存句柄,因此如果元素重复某个地方它不会重复数据,它只会将副本的$ ref属性设置为原始的$ id.在这种情况下,必须将此属性设置为Newtonsoft.Json.PreserveReferencesHandling.Objects,并且可以使用Sajid的答案. (7认同)
  • 我删除了我的帖子.我在这里添加我的答案作为评论.因此,它可以作为"议会"建议的参考.删除myObject.$ id; 就是这样. (2认同)

Tyl*_*Y86 8

如果由于某种原因你正在使用自定义的ContractResolver,请看看这个其他堆栈溢出;

尽管将PreserveReferencesHandling设置为"None",Json.Net仍向EF对象添加$ id


小智 5

为我的 Web API 删除 JSON 中的 $id。我为我的类对象包含了 [JsonObject(IsReference = false)],为属于对象类型的属性包含了 [JsonProperty(IsReference = false)]。在我的例子中,RespObj 属性是通用类型 T,可以接受我传递给它的任何对象类型,包括集合,所以我不得不使用 [JsonProperty(IsReference = false)] 来去除序列化 JSON 字符串中的 $id。

我没有更改我的 WebApiConfig,因为我使用的是 WEB API 的 MVC 帮助页面,它要求我在我的 webApiconfig 中有此配置:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
        json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
Run Code Online (Sandbox Code Playgroud)

类对象

[DataContract(IsReference = true)]
[JsonObject(IsReference = false)]
public class QMResponse<T> where T : new()
{
    public QMResponse()
    {

    }

    /// <summary>
    /// The response code
    /// </summary> 
    public string RespCode { get; set; }

    /// <summary>
    /// The response message
    /// </summary> 
    public string RespMxg { get; set; }

    /// <summary>
    /// The exception message
    /// </summary> 
    public string exception { get; set; }

    /// <summary>
    /// The object type returned
    /// </summary>         
    [JsonProperty(IsReference = false)]
    public T RespObj { get; set; }

    /// <summary>
    /// No of records returned
    /// </summary> 
    public long RecordCount { get; set; }

    /// <summary>
    /// The Session Object
    /// </summary> 
    public string session_id { get; set; }

}
Run Code Online (Sandbox Code Playgroud)