c# - Json.NET - 控制类对象属性反序列化

标签 c# json.net

我有一个用 JSON.Net 反序列化的模型类 Link

public class Link
{
    [JsonConstructor]
    internal Link(int id)
    {
        Id = id;
    }

    public int Id { get; internal set; }

    [JsonProperty("title")]
    public string Title { get; internal set; }

    [JsonProperty("description")]
    public string Description { get; internal set; }

... and so on

    public Avatar AuthorAvatar { get; internal set; }
}

Avatar 包含三个属性:DefaultImageUriSmallImageUriMediumImageUri。是否可以在 Link 对象反序列化上创建 Avatar 对象,这将使用:author_avatarauthor_avatar_smallauthor_avatar_medium json 字段?

最佳答案

我相信您可以通过编写自己的 JsonConverter 来实现此目的,这里是一个示例(我省略了序列化部分,但实现与反序列化非常相似):

示例:

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
    }

关于c# - Json.NET - 控制类对象属性反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27460522/

相关文章:

c# - SQL 服务器错误 : ExecuteNonQuery: Connection property has not been initialized

c# - 使自动生成的部分类实现自定义接口(interface)

c# - Datagridview 列索引更新后返回 0

c# - 使用 C#/Json 序列化 Web 服务中的结构

ios - 使用 setValuesForKeysWithDictionary 和 JSON 设置 NSDate 时出现问题

c# - 如何实现将复杂类型序列化/反序列化为简单类型的 Newtonsoft JSON 转换器

elasticsearch - 在NEST Elasticsearch 查询中,file.filename返回null

c# - 如何判断 JSON 对象是否为数组?

c# - 读取 SOAP 消息响应 ASP.NET MVC4 C#

C# 将 JSON 写入不带反斜杠的文件