Tôi có một lớp học như vậy:Làm cách nào để lấy tên của một JsonProperty trong JSON.Net?
[JsonObject(MemberSerialization.OptIn)]
public class foo
{
[JsonProperty("name_in_json")]
public string Bar { get; set; }
// etc.
public Dictionary<string, bool> ImageFlags { get; set; }
}
Các JSON được tạo ra từ một tập tin CSV ban đầu, mỗi dòng đại diện cho một đối tượng foo - đó là về cơ bản phẳng, vì vậy tôi cần để ánh xạ một số phím để imageflags.
Tôi đã cố gắng viết một CustomCreationConverter dựa trên ví dụ here.
Điều này dường như lập bản đồ các cờ phạt, nhưng nó không đặt thuộc tính bình thường - nó tìm 'thanh' thay vì 'name_in_json'.
Làm cách nào để tôi nhận được giá trị 'name_in_json' cho đối tượng kiểu foo?
chỉnh sửa:
giải pháp hiện tại:
var custAttrs = objectType.GetProperties().Select(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), true)).ToArray();
var propNames = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();
Dictionary<string, string> objProps = new Dictionary<string, string>();
for (int i = 0; i < propNames.Length; i++)
// not every property has json equivalent...
if (0 == custAttrs[i].Length)
{
continue;
}
var attr = custAttrs[i][0] as JsonPropertyAttribute;
objProps.Add(attr.PropertyName.ToLower(), propNames[i].ToLower());
}