我有一个要使用NewtonSoft Json.Net序列化到Json的对象。 对象相对较大,生成的Json约为300kb,但是序列化过程大约需要60秒。

要序列化的对象只是普通的POCO。

我正在使用的代码是

string json = Newtonsoft.Json.JsonConvert.SerializeObject(data, Formatting.Indented);

有什么事情可以做以加快序列化,添加属性等。

编辑:我刚刚用ServiceStack.Text Json序列化程序进行了测试,这需要48秒,仍然很慢。

[Serializable]
public class AppointmentItemViewModel 
{
    public AppointmentItemViewModel()
    {
        Data = new AppointmentData();
        Statuses = new List<Status>();
        ClosedDays = new List<ClosedDay>();
        OpenHours = new List<OpenHours>();
    }

    public int CurrentDay { get; set; }

    public int CurrentMonth { get; set; }

    public int CurrentYear { get; set; }

    public int Day { get; set; }

    public int Month { get; set; }

    public int Year { get; set; }

    public int FirstHour { get; set; }

    public int LastHour { get; set; }

    public int CurrentHour { get; set; }

    public int Step { get; set; }

    public bool StaffOnlyBookOwn { get; set; }

    public bool AllowPastAppointments { get; set; }

    public bool AllowBlocks { get; set; }

    public bool AllowGoogleCalendarSync { get; set; }

    public long CurrentUser { get; set; }

    public string DebugInfo { get; set; }

    public bool HasResources { get; set; }

    public string OrganisationId { get; set; }

    public string DefaultTab { get; set; }

    public string StartDay { get; set; }

    public bool AppointmentBreaksOnWeek { get; set; }

    public bool AppointmentBreaksOnMonth { get; set; }

    public AppointmentData Data { get; set; }

    public IEnumerable<Status> Statuses { get; set; }

    public IEnumerable<LocationStaff> Staff { get; set; }

    public IEnumerable<ClosedDay> ClosedDays { get; set; }

    public IEnumerable<OpenHours> OpenHours { get; set; }

    public IUserContext UserContext()
    {
        return ServiceLocator.Current.GetInstance<IUserContext>();
    }

    public override string ToString()
    {
        // Serialize the Json
        var sb = new StringBuilder();

        StringWriter sw = new StringWriter(sb);

        using (JsonWriter writer = new JsonTextWriter(sw))
        {
            writer.WriteStartObject();

            WriteProperty(writer, "CurrentDay", this.CurrentDay);
            WriteProperty(writer, "CurrentMonth", this.CurrentMonth);
            WriteProperty(writer, "CurrentYear", this.CurrentYear);
            WriteProperty(writer, "Day", this.Day);
            WriteProperty(writer, "Month", this.Month);
            WriteProperty(writer, "Year", this.Year);
            WriteProperty(writer, "FirstHour", this.FirstHour);
            WriteProperty(writer, "LastHour", this.LastHour);
            WriteProperty(writer, "CurrentHour", this.CurrentHour);
            WriteProperty(writer, "Step", this.Step);
            WriteProperty(writer, "StaffOnlyBookOwn", this.StaffOnlyBookOwn);
            WriteProperty(writer, "AllowPastAppointments", this.AllowPastAppointments);
            WriteProperty(writer, "AllowBlocks", this.AllowBlocks);
            WriteProperty(writer, "AllowGoogleCalendarSync", this.AllowGoogleCalendarSync);
            WriteProperty(writer, "CurrentUser", this.CurrentUser);
            WriteProperty(writer, "HasResources", this.HasResources);
            WriteProperty(writer, "OrganisationId", this.OrganisationId);
            WriteProperty(writer, "DefaultTab", this.DefaultTab);
            WriteProperty(writer, "StartDay", this.StartDay);
            WriteProperty(writer, "AppointmentBreaksOnWeek", this.AppointmentBreaksOnWeek);
            WriteProperty(writer, "AppointmentBreaksOnMonth", this.AppointmentBreaksOnMonth);


            writer.WritePropertyName("Statuses");
            writer.WriteStartArray();
            foreach (var item in this.Statuses)
            {
                writer.WriteStartObject();
                WriteProperty(writer, "Id", item.Id);
                WriteProperty(writer, "Description", item.Description);
                WriteProperty(writer, "Color", item.Color);
                writer.WriteEndObject();
            }
            writer.WriteEndArray();


            writer.WritePropertyName("Staff");
            writer.WriteStartArray();
            foreach (var item in this.Staff)
            {
                writer.WriteStartObject();
                WriteProperty(writer, "Id", item.Id);
                WriteProperty(writer, "Name", item.Name);
                writer.WriteEndObject();
            }
            writer.WriteEndArray();


            writer.WritePropertyName("ClosedDays");
            writer.WriteStartArray();
            foreach (var item in this.ClosedDays)
            {
                writer.WriteStartObject();
                WriteProperty(writer, "Year", item.Year);
                WriteProperty(writer, "Month", item.Month);
                WriteProperty(writer, "Day", item.Day);
                writer.WriteEndObject();
            }
            writer.WriteEndArray();


            writer.WritePropertyName("OpenHours");
            writer.WriteStartArray();
            foreach (var item in this.OpenHours)
            {
                writer.WriteStartObject();
                WriteProperty(writer, "DayOfWeek", item.DayOfWeek);
                WriteProperty(writer, "OpenHour", item.OpenHour);
                WriteProperty(writer, "CloseHour", item.CloseHour);
                writer.WriteEndObject();
            }
            writer.WriteEndArray();

            // Main data
            writer.WritePropertyName("Data");
            writer.WriteStartObject();

            writer.WritePropertyName("Appointments");
            writer.WriteStartArray();
            foreach (var item in this.Data.Appointments)
            {
                writer.WriteStartObject();

                WriteProperty(writer, "Id", item.Id);
                WriteProperty(writer, "AppointmentId", item.AppointmentId);
                WriteProperty(writer, "Year", item.Year);
                WriteProperty(writer, "Month", item.Month);
                WriteProperty(writer, "Day", item.Day);
                WriteProperty(writer, "StartHour", item.StartHour);
                WriteProperty(writer, "StartMinute", item.StartMinute);
                WriteProperty(writer, "EndHour", item.EndHour);
                WriteProperty(writer, "EndMinute", item.EndMinute);
                WriteProperty(writer, "ResourceId", item.ResourceId);
                WriteProperty(writer, "Description", item.Description);
                WriteProperty(writer, "Status", item.Status);
                WriteProperty(writer, "IsClass", item.IsClass);
                WriteProperty(writer, "ProcessingLength", item.ProcessingLength);
                WriteProperty(writer, "ClientId", item.ClientId);
                WriteProperty(writer, "ClientName", item.ClientName);
                WriteProperty(writer, "ClientPhone", item.ClientPhone);
                WriteProperty(writer, "ClientNotes", item.ClientNotes);
                WriteProperty(writer, "ClientHasMobile", item.ClientHasMobile);
                WriteProperty(writer, "ClassFull", item.ClassFull);
                WriteProperty(writer, "ClientWaiting", item.ClientWaiting);
                WriteProperty(writer, "PromotionCode", item.PromotionCode);
                WriteProperty(writer, "ArrivalNote", item.ArrivalNote);
                WriteProperty(writer, "Labels", item.Labels);
                WriteProperty(writer, "ReminderSent", item.ReminderSent);
                WriteProperty(writer, "Cancelled", item.Cancelled);


                writer.WritePropertyName("Items");
                writer.WriteStartArray();
                foreach (var appointmentItem in item.Items)
                {
                    writer.WriteStartObject();
                    WriteProperty(writer, "Name", appointmentItem.Name);
                    WriteProperty(writer, "Length", appointmentItem.Length);
                    WriteProperty(writer, "ProcessingTime", appointmentItem.ProcessingTime);
                    WriteProperty(writer, "Resource", appointmentItem.Resource);
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();

                writer.WriteEndObject();
            }
            writer.WriteEndArray();

            writer.WritePropertyName("Resources");
            writer.WriteStartArray();
            foreach (var item in this.Data.Resources)
            {
                writer.WriteStartObject();

                WriteProperty(writer, "Id", item.Id);
                WriteProperty(writer, "Name", item.Name);
                WriteProperty(writer, "BlockLength", item.BlockLength);
                WriteProperty(writer, "StartHour", item.StartHour);
                WriteProperty(writer, "EndHour", item.EndHour);


                writer.WritePropertyName("Breaks");
                writer.WriteStartArray();
                foreach (var breakItem in item.Breaks)
                {
                    writer.WriteStartObject();
                    WriteProperty(writer, "Year", breakItem.Year);
                    WriteProperty(writer, "Month", breakItem.Month);
                    WriteProperty(writer, "Day", breakItem.Day);
                    WriteProperty(writer, "DayOfWeek", breakItem.DayOfWeek);
                    WriteProperty(writer, "StartHour", breakItem.StartHour);
                    WriteProperty(writer, "StartMinute", breakItem.StartMinute);
                    WriteProperty(writer, "Length", breakItem.Length);
                    WriteProperty(writer, "Description", breakItem.Description);
                    WriteProperty(writer, "OtherBreak", breakItem.OtherBreak);
                    WriteProperty(writer, "UserBreak", breakItem.UserBreak);
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();


                writer.WritePropertyName("OpenCloseBreaks");
                writer.WriteStartArray();
                foreach (var breakItem in item.OpenCloseBreaks)
                {
                    writer.WriteStartObject();
                    WriteProperty(writer, "Year", breakItem.Year);
                    WriteProperty(writer, "Month", breakItem.Month);
                    WriteProperty(writer, "Day", breakItem.Day);
                    WriteProperty(writer, "DayOfWeek", breakItem.DayOfWeek);
                    WriteProperty(writer, "StartHour", breakItem.StartHour);
                    WriteProperty(writer, "StartMinute", breakItem.StartMinute);
                    WriteProperty(writer, "Length", breakItem.Length);
                    WriteProperty(writer, "Description", breakItem.Description);
                    WriteProperty(writer, "OtherBreak", breakItem.OtherBreak);
                    WriteProperty(writer, "UserBreak", breakItem.UserBreak);
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();

                writer.WriteEndObject();
            }
            writer.WriteEndArray();

            writer.WriteEndObject();
        }

        return sb.ToString();
    }

    private void WriteProperty(JsonWriter writer, string name, object value)
    {
        writer.WritePropertyName(name);

        if (value == null)
        {
            writer.WriteNull();
        }
        else
        {
            writer.WriteValue(value);
        }
    }

}

[Serializable]
public class AppointmentData
{
    public IEnumerable<ExternalEvent> ExteralEvents { get; set; }

    public IEnumerable<Appointment> Appointments { get; set; }

    public IEnumerable<Resource> Resources { get; set; }
}

[Serializable]
public class ClosedDay
{
    public int Year { get; set; }

    public int Month { get; set; }

    public int Day { get; set; }
}

[Serializable]
public class Appointment
{
    public long Id { get; set; }

    public long AppointmentId { get; set; }

    public int Year { get; set; }

    public int Month { get; set; }

    public int Day { get; set; }

    public int StartHour { get; set; }

    public int StartMinute { get; set; }

    public int EndHour { get; set; }

    public int EndMinute { get; set; }

    public long ResourceId { get; set; }

    public string Description { get; set; }

    public long Status { get; set; }

    public bool IsClass { get; set; }

    public int ProcessingLength { get; set; }


    public long ClientId { get; set; }

    public string ClientName { get; set; }

    public string ClientPhone { get; set; }

    public string ClientNotes { get; set; }

    public bool ClientHasMobile { get; set; }

    public bool ClassFull { get; set; }

    public string ClientWaiting { get; set; }

    public string PromotionCode { get; set; }

    public string ArrivalNote { get; set; }

    public string Labels { get; set; }

    public bool ReminderSent { get; set; }

    public bool Cancelled { get; set; }

    public IEnumerable<AppointmentItems> Items { get; set; }
}

[Serializable]
public class AppointmentItems
{
    public string Name { get; set; }

    public int Length { get; set; }

    public int ProcessingTime { get; set; }

    public string Resource { get; set; }
}

[Serializable]
public class OpenHours
{
    public int DayOfWeek { get; set; }

    public int? OpenHour { get; set; }

    public int? CloseHour { get; set; }
}

[Serializable]
public class Resource
{
    public Resource()
    {
        Breaks = new List<ResourceBreak>();
        Blocks = new List<ResourceBlock>();
        OpenCloseBreaks = new List<ResourceBreak>();
    }

    public long Id { get; set; }

    public string Name { get; set; }

    public int BlockLength { get; set; }

    public int StartHour { get; set; }

    public int EndHour { get; set; }

    public IEnumerable<ResourceBreak> Breaks { get; set; }

    public IEnumerable<ResourceBlock> Blocks { get; set; }

    public IEnumerable<ResourceBreak> OpenCloseBreaks { get; set; }

}

[Serializable]
public class ExternalEvent
{
    public long Id { get; set; }

    public int Year { get; set; }

    public int Month { get; set; }

    public int Day { get; set; }

    public int DayOfWeek { get; set; }

    public int StartHour { get; set; }

    public int StartMinute { get; set; }

    public int EndHour { get; set; }

    public int EndMinute { get; set; }

    public int Length { get; set; }

    public string Description { get; set; }
}

[Serializable]
public class ResourceBreak
{
    public int Year { get; set; }

    public int Month { get; set; }

    public int Day { get; set; }

    public int DayOfWeek { get; set; }

    public int StartHour { get; set; }

    public int StartMinute { get; set; }

    public int Length { get; set; }

    public string Description { get; set; }

    public bool OtherBreak { get; set; }

    public bool UserBreak { get; set; }
}

[Serializable]
public class ResourceBlock
{
    public int StartHour { get; set; }

    public int StartMinute { get; set; }

    public int Length { get; set; }
}

[Serializable]
public class Status
{
    public long Id { get; set; }

    public string Description { get; set; }

    public int Color { get; set; }
}

[Serializable]
public class LocationStaff
{
    public long Id { get; set; }

    public string Name { get; set; }
}

===============>>#1 票数:14 已采纳

您是否尝试过使用JSON.NET将对象手动序列化为JSON? 当您拥有大量数据和许多属性时,我发现它的速度要快得多。 下面是一个示例:

public static string Serialise(YourObject data)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

using (JsonWriter writer = new JsonTextWriter(sw))
{
    writer.WriteStartObject();

    writer.WritePropertyName("propertyName1");

    if (data.Property1 == null)
    {
        writer.WriteNull();
    }
    else
    {
        writer.WriteValue(data.Property1);
    }

    writer.WritePropertyName("propertyName2");

    writer.WriteStartArray();

    foreach (var something in data.CollectionProperty)
    {
        writer.WriteStartObject();

        writer.WritePropertyName("p1");
        writer.WriteValue(something.prop1);

        writer.WritePropertyName("p2");
        writer.WriteValue(something.prop2);

        writer.WritePropertyName("p3");
        writer.WriteValue(something.prop3);

        writer.WriteEndObject();
    }

    writer.WriteEndArray();

    writer.WriteEndObject();
}

return sb.ToString();
}

这意味着需要做更多的工作,但是如果要达到目标,您将找不到更快的选择。

===============>>#2 票数:6

您应该为乔恩·贝拉米(Jon Bellamy)给出答案的要点,但是这里有一些详细信息:

我正在处理的项目也遇到了同样的问题,我按照本页上的建议解决了这个问题:

http://www.newtonsoft.com/json/help/html/Performance.htm

具体来说,他们建议在性能至关重要时手动序列化对象:

public static string ToJson(this Person p)
{
    StringWriter sw = new StringWriter();
    JsonTextWriter writer = new JsonTextWriter(sw);

    // {
    writer.WriteStartObject();

    // "name" : "Jerry"
    writer.WritePropertyName("name");
    writer.WriteValue(p.Name);

    // "likes": ["Comedy", "Superman"]
    writer.WritePropertyName("likes");
    writer.WriteStartArray();
    foreach (string like in p.Likes)
    {
        writer.WriteValue(like);
    }
    writer.WriteEndArray();

    // }
    writer.WriteEndObject();

    return sw.ToString();
}

我在VB中的示例如下所示:

    Public Function SerializeWords(ByRef oWords As List(Of Word))
        Dim sb As New StringBuilder
        Dim sw As New IO.StringWriter(sb)
        Using oWriter As Newtonsoft.Json.JsonWriter = New Newtonsoft.Json.JsonTextWriter(sw)
            With oWriter
                .WriteStartArray()
                For Each oWord As Word In oWords
                    .WriteStartObject()

                    .WritePropertyName("ID")
                    .WriteValue(oWord.ID)

                    .WritePropertyName("Phonics")
                    .WriteValue(oWord.Phonics)

                    .WritePropertyName("Word_")
                    .WriteValue(oWord.Word_)

                    .WritePropertyName("WordLength")
                    .WriteValue(oWord.WordLength)

                    .WriteEndObject()
                Next
                .WriteEndArray()

            End With
        End Using
        Return sb.ToString

    End Function

注意这两个函数是如何强类型化的。 我相信,当您使用Newtonsoft.Json.JsonConvert.SerializeObject()它是使用反射来完成工作的(当您拥有许多具有许多属性的对象时,这实际上可以累加起来)。

无论如何...一旦编写了自己的序列化程序,我序列化250个“ Word”对象的列表的时间就从使用JsonConvert.SerializeObject()方法的28秒变为使用自己的函数的31毫秒。

===============>>#3 票数:0

这仍然使用了序列化器( 内部使用了反射 ),最终解决了我的速度问题+我不必手动输入所有内容。我不知道JsonConvert.SerializeObject()在内部是否不同于serializer.Serialize()但我想我希望能对您有所帮助

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

using(JsonWriter writer = new JsonTextWriter(sw))
 {
  var serializer = new JsonSerializer();
  serializer.Serialize(writer, data);
 } 

  ask by Craig translate from so

未解决问题?本站智能推荐:

2回复

JSON newtonsoft反序列化

我必须解析以下格式的Web API。 请注意,我无法更改JSON的格式。 它将始终以以下格式出现: 当我尝试在Newtonsoft中解析它时,出现以下错误消息: 无法将当前json对象反序列化,因为(eg {“ name”:“ value”})成为类型,因为该类型需要jso
1回复

Newtonsoft Json反序列化器无法正常工作

我正在构建一个应用程序来处理在C#环境中填写的人员调查。 当我正常运行应用程序时,一切正常,反序列化工作,序列化工作,一切正常。 当我发送调查时,一切都会好起来的。 当我重新打开应用程序时,程序会自动向服务器发送请求以检索可用的调查。 但当他试图反序列化json时,他发现他需要制
3回复

Newtonsoft JSON反序列化

我的JSON如下: 我找到了C#的Newtonsoft JSON.NET反序列化库。 我尝试如下使用它: 如何访问JsonDe对象以获取所有“类型”数据? 我尝试了一个循环,但由于对象没有枚举器而无法正常工作。
1回复

NewtonSoft JSON序列化器和UTF8支持[关闭]

我有一个使用NewtonSoft的JSON序列化器的简单方法,我喜欢它(简单,返回格式化JSON)。 但是我似乎无法正确地序列化UTF8字符(它们显示为问号,即'?'),这些字符位于对象内的字符串中。 我正在使用的代码是:
1回复

使用newtonsoft json反序列化json对象

我有一个像 而且我需要将此json反序列化到我的类对象中。 我的课 我们如何使用newtonsoft.json实现这一目标。 谁能帮忙。 提前致谢
2回复

JSON字符串序列化(Newtonsoft.JSON)

我得到一个JSON字符串作为HTTP响应。 该字符串如下所示: 我有Newtonsoft.Json库,并且有Response和Item类: 我像这样反序列化: 它不起作用,“ r”保持为空。 我在哪里错了,为什么? 它正在编译,没有任何异常。
3回复

Newtonsoft JSON DeserializeObject序列化对象的反序列化

我返回了以下要反序列化的JSON字符串,但是在填写对象属性值时遇到问题。 这是返回的JSON字符串: 现在,我通过以下方法指定了ClientData类: 转换中我在做什么错? 我以为只要指定就可以了: 但是,这不会产生任何结果。 我认为问题可能在于如何构造JSO
4回复

Newtonsoft Json序列化/反序列化嵌套属性

我有以下课程结构 我设置以下值: 当我序列化类“ mainClass”时,我得到以下Json(对我来说这是绝对清楚的): 在某些情况下,我需要序列化为以下内容: 子类的字段名称始终为“ Value”,该怎么做? (我还需要对相同结构进行反序列化)
1回复

Newtonsoft Json序列化条件序列化突然爆发

我遇到了一个奇怪的问题,Newtonsoft Json条件序列化意外地踢了。 我把它简化为一个简单的例子(我们使用的是newtonsoft json 5.0.8): 以上输出: 看来有一个名为'xSpecified'的bool属性,其中'x'与另一个属性的名称匹配,作为条件序列
1回复

Newtonsoft反序列化JSON片段对象

我正在反序列化具有两种类型的两个片段的json。 一个是对象(客户端应用程序中的.Net对象),另一个是对象列表。 那么,我是否只是将JObject中的数据作为JToken并将其转换为所需的.NET对象类型? 我该怎么办? 目前,我正在尝试执行以下操作: 但是我仍然坚持如何将