Có, điều này có thể được thực hiện bằng cách sử dụng tùy chỉnh ContractResolver
.
Bạn không hiển thị bất kỳ mã nào, vì vậy tôi sẽ chỉ tạo một ví dụ. Giả sử tôi có một lớp học Foo
như được hiển thị bên dưới. Tôi muốn các thuộc tính Id
và Name
trong đầu ra tuần tự hóa, nhưng tôi chắc chắn không quan tâm đến số AlternateName
và Color
. Tôi đã đánh dấu những người có số [JsonIgnore]
. Tôi muốn mô tả xuất hiện, nhưng đôi khi điều này có thể thực sự dài, vì vậy tôi đã sử dụng tùy chỉnh JsonConverter
để giới hạn độ dài của nó. Tôi cũng muốn sử dụng tên thuộc tính ngắn hơn cho mô tả, vì vậy tôi đã đánh dấu nó bằng [JsonProperty("Desc")]
.
class Foo
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public string AlternateName { get; set; }
[JsonProperty("Desc")]
[JsonConverter(typeof(StringTruncatingConverter))]
public string Description { get; set; }
[JsonIgnore]
public string Color { get; set; }
}
Khi tôi serialize một thể hiện những điều trên ...
Foo foo = new Foo
{
Id = 1,
Name = "Thing 1",
AlternateName = "The First Thing",
Description = "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
Color = "Yellow"
};
string json = JsonConvert.SerializeObject(foo, Formatting.Indented);
... Tôi nhận được kết quả này:
{
"Id": 1,
"Name": "Thing 1",
"Desc": "This is some lengthy text describing Thing 1 "
}
Bây giờ, chúng ta hãy nói rằng đôi khi tôi muốn nhận được đầu ra JSON đầy đủ, bỏ qua các tùy chỉnh của tôi. Tôi có thể sử dụng tùy chỉnh ContractResolver
để lập trình "không chính xác" các thuộc tính từ lớp. Dưới đây là các mã cho phân giải:
class IgnoreJsonAttributesResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (var prop in props)
{
prop.Ignored = false; // Ignore [JsonIgnore]
prop.Converter = null; // Ignore [JsonConverter]
prop.PropertyName = prop.UnderlyingName; // restore original property name
}
return props;
}
}
Để sử dụng bộ giải quyết, tôi thêm nó vào JsonSerializerSettings
và vượt qua các thiết lập để serializer như thế này:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new IgnoreJsonAttributesResolver();
settings.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(foo, settings);
Sản lượng hiện nay bao gồm các thuộc tính bỏ qua, và mô tả không còn cắt ngắn:
{
"Id": 1,
"Name": "Thing 1",
"AlternateName": "The First Thing",
"Description": "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
"Color": "Yellow"
}
Full demo ở đây: https://dotnetfiddle.net/WZpeWt
lẽ hiển thị một số mã như thế nào bạn có quản lý để tùy chỉnh JSON.Net cho đến nay. –