类的自定义JSON序列化 [英] Custom Json Serialization of class

查看:144
本文介绍了类的自定义JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码结构如下图所示。

I have code structured like below.

public class Stats
{
        public string URL { get; set; }
        public string Status { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int Length { get; set; }
}

 public class UrlStats
 {
        public string URL { get; set; }
        public int TotalPagesFound { get; set; }
        public List<Stats> TotalPages { get; set; }
        public int TotalTitleTags { get; set; }
        public List<Stats> TotalTitles { get; set; }
        public int NoDuplicateTitleTags { get; set; }
        public List<Stats> DuplicateTitles { get; set; }
        public int NoOverlengthTitleTags { get; set; }
        public List<Stats> OverlengthTitles { get; set; }
 }



基本上我扫描一个网站,如标题标签的统计数据,重复的标题,等等。

Basically i am scanning a website for statistics like title tags, duplicate titles, etc.

我使用jQuery和使AJAX调用web服务和检索网址的统计,而进程正在运行,显示用户的URL统计迄今收集的,因为它需要相当的时间扫描各大网站。所以,每5秒后,我从服务器检索统计信息。现在的问题是所有的列表变量数据,我需要在最后发送扫描处理完成后,不会在更新。这是怎么回事,现在的列表<统计>这是大数据块更新时也被送到可变数据,我想只发送 INT 键入时都必须出示流程更新变量。

I am using JQuery and making AJAX calls to webservice and retrieving url stats while the process is running to show user url stats by far collected since it takes quite a time to scan a big website. So after every 5 seconds i retrieve stats from server. Now the problem is all the List variable data i need to send at the end when scanning processing is complete, not during updates. What's happening right now the List<Stats> variable data is also sent during updates which is big chunk of data and i want to send only int type variables which are required to show process updates.

从互联网上搜索我无法找到解决我的问题,什么有用的东西,我发现JSON。 NET是非常好的库,但我真的不知道如何正确使用它来得到我想要的东西。

From searching on internet i couldn't find anything useful solving my problem and i found that Json.NET is very good library but i really don't know how to properly use it to get what i want.

基本上我寻找序列取决于性能其数据类型在运行时,如果可能的。

在此先感谢,

迪内希

推荐答案

有你的问题,有两种不同的方法。

There are two different approaches for your problem.

您应该选择第一个,如果你要更频繁地改变你的类,因为第一种方法可以防止你忘了序列化新添加的属性。此外它更可重复使用的,如果你想添加要被序列化方式相同的另一个类。

You should choose the first one if you are going to change your classes more often because the first approach prevents that you forget to serialize a newly added property. Furthermore it is much more reusable if you want to add another classes you want to be serialized the same way.

如果你只有这两个类,它是最有可能的,他们再不会改变,你可以选择第二种方法,让您的解决方案很简单。

If you have only these two classes and it's most likely that they're not going to change you can choose the second approach to keep your solution simple.

第一种方法是使用自定义的 JsonConverter 这仅包括已键入 INT 属性序列化类或结构。该代码可能是这样的:

The first approach is to use a custom JsonConverter which serializes a class or struct by only including properties which have type int. The code might look like this:

class IntPropertyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // this converter can be applied to any type
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // we currently support only writing of JSON
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value == null)
        {
            serializer.Serialize(writer, null);
            return;
        }

        // find all properties with type 'int'
        var properties = value.GetType().GetProperties().Where(p => p.PropertyType == typeof(int));

        writer.WriteStartObject();

        foreach (var property in properties)
        {
            // write property name
            writer.WritePropertyName(property.Name);
            // let the serializer serialize the value itself
            // (so this converter will work with any other type, not just int)
            serializer.Serialize(writer, property.GetValue(value, null));
        }

        writer.WriteEndObject();
    }
}



然后,你必须来装饰与类 JsonConverterAttribute

[JsonConverter(typeof(IntPropertyConverter))]
public class UrlStats
{
    // ...
}

声明:的这段代码已经过测试,只有极大致

Disclaimer: This code has been tested only very roughly.

第二个解决方案看起来有点简单:你可以使用 JsonIgnoreAttribute 来装点你想要的属性为排除序列化。此外,还可以从黑名单到白名单的明确,包括要序列化的属性进行切换。这是一个有点示例代码:

The second solution looks a bit simpler: You can use the JsonIgnoreAttribute to decorate the attributes you want to exclude for serialization. Alternatively you can switch from "blacklisting" to "whitelisting" by explicitly including the attributes you want to serialize. Here is a bit of sample code:

黑名单:(我已经重新排序为更好地了解属性)

Blacklisting: (I've reordered the properties for a better overview)

[JsonObject(MemberSerialization.OptOut)] // this is default and can be omitted
public class UrlStats
{
    [JsonIgnore] public string URL { get; set; }
    [JsonIgnore] public List<Stats> TotalPages { get; set; }
    [JsonIgnore] public List<Stats> TotalTitles { get; set; }
    [JsonIgnore] public List<Stats> DuplicateTitles { get; set; }
    [JsonIgnore] public List<Stats> OverlengthTitles { get; set; }

    public int TotalPagesFound { get; set; }
    public int TotalTitleTags { get; set; }
    public int NoDuplicateTitleTags { get; set; }
    public int NoOverlengthTitleTags { get; set; }
}



白名单:(也重新排序)

[JsonObject(MemberSerialization.OptIn)] // this is important!
public class UrlStats
{
    public string URL { get; set; }
    public List<Stats> TotalPages { get; set; }
    public List<Stats> TotalTitles { get; set; }
    public List<Stats> DuplicateTitles { get; set; }
    public List<Stats> OverlengthTitles { get; set; }

    [JsonProperty] public int TotalPagesFound { get; set; }
    [JsonProperty] public int TotalTitleTags { get; set; }
    [JsonProperty] public int NoDuplicateTitleTags { get; set; }
    [JsonProperty] public int NoOverlengthTitleTags { get; set; }
}

这篇关于类的自定义JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆