简体   繁体   English

将 object 转换为 json 字符串时忽略属性

[英]Ignore property when converting object to json string

So i have a REST API that works with a JSON based on OData exchange.所以我有一个 REST API 与基于 OData 交换的 JSON 一起使用。 In a OData type there is a ID property i want to read so i can do some checking on it.在 OData 类型中,有一个我想读取的 ID 属性,因此我可以对其进行一些检查。 However when i want to write back to the webserver the ID property must not be present in the response JSON string.但是,当我想写回网络服务器时,ID 属性不能出现在响应 JSON 字符串中。 So it has to be a write-only property, but simply changing a property to write-only prevents be to check what the value is of that property.所以它必须是一个只写属性,但简单地将一个属性更改为只写可以防止检查该属性的值是什么。

For example, i create a new product:例如,我创建了一个新产品:

Public Class Product
  Public property ID as integer
  Public property Title as string
End class

GET response:获取响应:

{
  "ID" = 1,
  "Title" = "Cool product!"
}

POST Wrong:发布错误:

{
  "ID" = 1, <---- ignore this value
  "Title" = "Cool product! Changed!"
}

POST Should be: POST 应该是:

{
  "Title" = "Cool product! Changed!"
}

The webserver uses OData网络服务器使用 OData

Using the attribute JsonIgnore doesn't fix it because the value of the REST response isn't serialized then.使用属性JsonIgnore并不能修复它,因为 REST 响应的值没有被序列化。

This is for WPF and not ASP.Net这是针对 WPF 而不是 ASP.Net

JSON.NET supports conditional property serialization using a method that returns a bool and has the same name as the property with a ShouldSerialize prefix: JSON.NET 支持条件属性序列化,该方法使用返回bool且与带有 ShouldSerialize 前缀的属性同名的方法:

public class Product
{
    public int Id { get; set; }
    public string Title { get; set; }

    public bool ShouldSerializeId() => false;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM