Skip to content

Commit d034580

Browse files
committed
Added converter to improve object serialization
1 parent 758e6a4 commit d034580

File tree

3 files changed

+69
-2
lines changed

3 files changed

+69
-2
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
namespace ElectronNET.API.Entities;
2+
3+
public class PageSize
4+
{
5+
private readonly string _value;
6+
7+
public PageSize()
8+
{
9+
}
10+
11+
private PageSize(string value) : this() => _value = value;
12+
13+
public double Height { get; set; }
14+
15+
public double Width { get; set; }
16+
17+
public static implicit operator string(PageSize pageSize) => pageSize?._value;
18+
19+
public static implicit operator PageSize(string value) => new(value);
20+
}

src/ElectronNET.API/API/Entities/PrintToPDFOptions.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
namespace ElectronNET.API.Entities;
1+
using ElectronNET.Converter;
2+
using Newtonsoft.Json;
3+
4+
namespace ElectronNET.API.Entities;
25

36
/// <summary>
47
///
@@ -30,7 +33,8 @@ public class PrintToPDFOptions
3033
/// `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing
3134
/// `height` and `width` in inches. Defaults to `Letter`.
3235
/// </summary>
33-
public object PageSize { get; set; } = "Letter";
36+
[JsonConverter(typeof(PageSizeConverter))]
37+
public PageSize PageSize { get; set; } = "Letter";
3438

3539
/// <summary>
3640
/// Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string,
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
using ElectronNET.API.Entities;
2+
using Newtonsoft.Json;
3+
using System;
4+
5+
namespace ElectronNET.Converter;
6+
7+
public class PageSizeConverter : JsonConverter<PageSize>
8+
{
9+
public override PageSize ReadJson(JsonReader reader, Type objectType, PageSize existingValue, bool hasExistingValue, JsonSerializer serializer)
10+
{
11+
if (reader.TokenType == JsonToken.String)
12+
{
13+
return (string)reader.Value;
14+
}
15+
else if (reader.TokenType == JsonToken.StartObject)
16+
{
17+
return serializer.Deserialize<PageSize>(reader);
18+
}
19+
else
20+
{
21+
throw new JsonSerializationException("Invalid value for PageSize. Expected true, false, or an object.");
22+
}
23+
}
24+
25+
public override void WriteJson(JsonWriter writer, PageSize value, JsonSerializer serializer)
26+
{
27+
if (value is null)
28+
{
29+
writer.WriteUndefined();
30+
}
31+
32+
var str = (string)value;
33+
34+
if (str is not null)
35+
{
36+
writer.WriteValue(str);
37+
}
38+
else
39+
{
40+
serializer.Serialize(writer, value);
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)