난 당신이 여기에 예를 JsonConverter
자신입니다 작성하여이를 수 있다고 믿는다 (I 직렬화 부분을 생략하지만, 구현은 매우 유사하다 드 직렬화) :
샘플 :
class Program
{
private static void Main(string[] args)
{
var json = @"{
id:1,
title: 'link title',
description: 'link description',
author_avatar:'link',
author_avatar_small:'small link',
author_avatar_medium:'medium link',
}";
var obj = JsonConvert.DeserializeObject<Link>(json);
}
}
클래스 정의 :
[JsonConverter(typeof(LinkSerializer))]
public class Link
{
[JsonConstructor]
public Link(int id)
{
Id = id;
}
[JsonIgnore]
public int Id { get; internal set; }
[JsonProperty("title")]
public string Title { get; internal set; }
[JsonProperty("description")]
public string Description { get; internal set; }
public Avatar AuthorAvatar { get; internal set; }
}
public class Avatar
{
[JsonProperty("author_avatar")]
public string DefaultImageUri { get; internal set; }
[JsonProperty("author_avatar_small")]
public string SmallImageUri { get; internal set; }
[JsonProperty("author_avatar_medium")]
public string MediumImageUri { get; internal set; }
}
사용자 정의 링크 시리얼 :
public class LinkSerializer : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof (Link) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
//NOTE:I changed .ctor to publec to simplify the process, we can also check for JsonConstructor attribute on constructors and the call appropriate one
var value = existingValue ?? Activator.CreateInstance(objectType, jObject["id"].Value<int>());
Populate(objectType, jObject, value);
var avatar = Activator.CreateInstance<Avatar>(); //Fill avatar object
Populate(avatar.GetType(),jObject,avatar);
objectType.GetProperty("AuthorAvatar").SetValue(value,avatar); //set avatar object
return value;
}
private static void Populate(Type objectType, JObject jObject, object value)
{
var properties =
objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var p in properties)
{
var ignore = p.GetCustomAttribute<JsonIgnoreAttribute>();
if (ignore != null)
continue;
var custom = p.GetCustomAttribute<JsonPropertyAttribute>();
var name = custom != null ? custom.PropertyName : p.Name;
var token = jObject[name];
var obj = token != null
? token.ToObject(p.PropertyType)
: p.PropertyType.IsValueType ? Activator.CreateInstance(p.PropertyType) : null;
p.SetValue(value, obj);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
//we just want to deserialize the object so we don't need it here, but the implementation would be very similar to deserialization
}
내가 난 그냥 세 "JsonProperty"에서 만들 수 AuthorAvatar 원하는 질문 ... t3chb0t @ – t3chb0t
이해가 안 무서워 - author_avatar을 author_avatar_small, author_avatar_medium 링크 클래스에 Uri AuthorAvatarDefault, Uri AuthorAvatarSmall, Uri AuthorAvatarMedium이라는 세 개의 Uri 필드가있는 대신 (아바타라는 다른 클래스에 '포장'하고 싶음) – fex