N
N
NewDevLab2019-06-05 17:50:38
.NET
NewDevLab, 2019-06-05 17:50:38

Normal option to optimize serialization to JSON?

Those. idea of ​​less code in JSON serialization.
This is the self-contained test code:

using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace JsonSerialize {
  class Program {
    static void Main(string[] args) {

      // Предложенный вариант - 6 сток
      Console.WriteLine("Предложенный вариант");
      using (JsonWriter writer = JsonTextWriterNew.GetJsonTextWriterNew(out StringBuilder sb1)) {
        writer.WriteStartObject();
        writer.WriteProperty("title", "Наше название");
        writer.WriteEndObject();
        Console.WriteLine(sb1.ToString());
      }

      // вместо этого варианта - 9 строк
      Console.WriteLine("вместо этого варианта");
      StringBuilder sb2 = new StringBuilder();
      StringWriter sw = new StringWriter(sb2);
      using (JsonWriter writer = new JsonTextWriter(sw)) {
        writer.WriteStartObject();
        writer.WritePropertyName("title");
        writer.WriteValue("Наше название");
        writer.WriteEndObject();
      }
      Console.WriteLine(sb2.ToString());
      Console.ReadKey();
    }
  }

}

namespace Newtonsoft.Json {
  public class JsonTextWriterNew : JsonWriter {

    private StringBuilder _sb;
    private StringWriter _sw;
    private JsonTextWriter _jtw;

    public static JsonTextWriter GetJsonTextWriterNew(out StringBuilder stringBuilder) {
      var jsonTextWriterExt = new JsonTextWriterNew();
      stringBuilder = jsonTextWriterExt._sb;
      return jsonTextWriterExt._jtw;
    }

    public JsonTextWriterNew() {
      _sb = new StringBuilder();
      _sw = new StringWriter(_sb);
      _jtw = new JsonTextWriter(_sw);
    }

    public override void Flush() {
      _jtw.Flush();
    }
  }

  public static class JsonWriterExtensions {
    public static void WriteProperty(this JsonWriter writer, string name, object value) {
      writer.WritePropertyName(name);
      writer.WriteValue(value);
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LiptonOlolo, 2019-06-05
@LiptonOlolo

Read: https://www.newtonsoft.com/json/help/html/Serializ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question