我有以下实体类:
public class FacebookComment : BaseEntity
{
[BsonId(IdGenerator = typeof(ObjectIdGenerator))]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
[JsonProperty("_id")]
public ObjectId Id { get; set; }
public int? OriginalId { get; set; }
public DateTime Date { get; set; }
public string Message { get; set; }
public string Sentiment { get; set; }
public string Author { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当此对象序列化为JSON时,我希望Id字段写为"_id":{...}.AFAIK,我只需要将所需的属性名传递给JsonProperty属性; 我应该好好去.但是,当我调用JsonConvert.SerializeObject; 它似乎忽略了我的属性并改为呈现:
{
Author: "Author name",
Date: "/Date(1321419600000-0500)/",
DateCreated: "/Date(1323294923176-0500)/",
Id: {
CreationTime: "/Date(0)/",
Increment: 0,
Machine: 0,
Pid: 0,
Timestamp: 0
},
Message: …Run Code Online (Sandbox Code Playgroud) 定义记录类时,如何将属性定位到参数、字段或属性?
例如,我想使用,JsonIgnore但这不能编译,因为它对字段或属性有属性使用限制:
record Person(string FirstName, string LastName, [JsonIgnore] int Age);
Run Code Online (Sandbox Code Playgroud) 我想使用带有 JsonPropertyName 属性的记录,但它导致了错误。这个不支持?任何解决方法?
public record QuoteResponse([JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);
Error CS0592 Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.
Run Code Online (Sandbox Code Playgroud)