1 | using System.IO;
|
---|
2 | using Newtonsoft.Json;
|
---|
3 | using Newtonsoft.Json.Linq;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.JsonInterface {
|
---|
6 | /// <summary>
|
---|
7 | /// Custom json writer for own formatting for templates.
|
---|
8 | /// It collapses arrays into a single line.
|
---|
9 | /// </summary>
|
---|
10 | public class SingleLineArrayJsonWriter : JsonTextWriter {
|
---|
11 | private bool isRangeArray = false;
|
---|
12 | public override void WriteStartArray() {
|
---|
13 |
|
---|
14 | if (isRangeArray) base.Formatting = Formatting.None;
|
---|
15 | base.WriteStartArray();
|
---|
16 | }
|
---|
17 |
|
---|
18 | public override void WritePropertyName(string name) {
|
---|
19 | base.Formatting = Formatting.Indented;
|
---|
20 | base.WritePropertyName(name);
|
---|
21 | isRangeArray =
|
---|
22 | name == nameof(IConcreteRestrictedJsonItem<int>.ConcreteRestrictedItems) ||
|
---|
23 | name == nameof(IValueJsonItem.Value) ||
|
---|
24 | name == nameof(IMatrixJsonItem.RowNames) ||
|
---|
25 | name == nameof(IMatrixJsonItem.ColumnNames);
|
---|
26 | }
|
---|
27 |
|
---|
28 | public override void WriteStartObject() {
|
---|
29 | base.Formatting = Formatting.Indented;
|
---|
30 | base.WriteStartObject();
|
---|
31 | }
|
---|
32 |
|
---|
33 | public override void WriteEndObject() {
|
---|
34 | base.Formatting = Formatting.Indented;
|
---|
35 | base.WriteEndObject();
|
---|
36 | }
|
---|
37 |
|
---|
38 | public SingleLineArrayJsonWriter(TextWriter writer) : base(writer) { }
|
---|
39 |
|
---|
40 | public static string Serialize(JToken token) {
|
---|
41 | JsonSerializer serializer = new JsonSerializer();
|
---|
42 | StringWriter sw = new StringWriter();
|
---|
43 | SingleLineArrayJsonWriter writer = new SingleLineArrayJsonWriter(sw);
|
---|
44 | writer.Formatting = Formatting.Indented;
|
---|
45 | serializer.Serialize(writer, token);
|
---|
46 | return sw.ToString();
|
---|
47 | }
|
---|
48 | }
|
---|
49 | }
|
---|