我有一个Asp.Net WebApi项目,我希望以Json格式和一个特定产品返回产品列表。
这是我的产品型号:
running db nodes = [node_1@host,node_2@host]
stopped db nodes = []
master node tables = []
remote = []
ram_copies = [foo,schema]
disc_copies = []
disc_only_copies = []
[{node_1@host,disc_copies},{node_2@host,ram_copies}] = [schema]
[{node_1@host,disc_only_copies},{node_2@host,ram_copies}] = [foo]
这是我的ApiController:
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4") // An example device ID
.build();
我想在一个特定产品中返回public class Product
{
public int Id { get; set; }
public string ShortString { get; set; }
public string LongString { get; set; }
}
字段,但不在产品列表中。 Json.Net库中是否有任何条件public class ProductController : ApiController
{
public IQueryable<Product> Get()
{
return Context.Products;
}
public IHttpActionResult Get(int id)
{
var p = Context.Products.FirstOrDefault(m => m.Id == id);
if (p == null)
return NotFound();
return Ok(p);
}
}
属性。
答案 0 :(得分:4)
您必须定义一个名为ShouldSerialize{PropertyName}
的公共方法,该方法会在您的类中返回bool。
public class Product
{
public int Id { get; set; }
public string ShortString { get; set; }
public string LongString { get; set; }
public bool ShouldSerializeLongString()
{
return (Id < 2); //maybe a more meaningful logic
}
}
测试
var l = new List<Product>()
{
new Product() {Id = 1, ShortString = "s", LongString = "l"},
new Product() {Id = 2, ShortString = "s", LongString = "l"}
};
Console.WriteLine(JsonConvert.SerializeObject(l));
结果是
[{ “ID”:1, “ShortString短”: “S”, “LongString”: “L”},{ “ID”:2 “ShortString短”: “S”}]