mirror of
https://github.com/ElectronNET/Electron.NET.git
synced 2026-02-04 05:34:51 +00:00
Added converter to improve object serialization
This commit is contained in:
20
src/ElectronNET.API/API/Entities/PageSize.cs
Normal file
20
src/ElectronNET.API/API/Entities/PageSize.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
namespace ElectronNET.API.Entities;
|
||||
|
||||
public class PageSize
|
||||
{
|
||||
private readonly string _value;
|
||||
|
||||
public PageSize()
|
||||
{
|
||||
}
|
||||
|
||||
private PageSize(string value) : this() => _value = value;
|
||||
|
||||
public double Height { get; set; }
|
||||
|
||||
public double Width { get; set; }
|
||||
|
||||
public static implicit operator string(PageSize pageSize) => pageSize?._value;
|
||||
|
||||
public static implicit operator PageSize(string value) => new(value);
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
namespace ElectronNET.API.Entities;
|
||||
using ElectronNET.Converter;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ElectronNET.API.Entities;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
@@ -30,7 +33,8 @@ public class PrintToPDFOptions
|
||||
/// `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing
|
||||
/// `height` and `width` in inches. Defaults to `Letter`.
|
||||
/// </summary>
|
||||
public object PageSize { get; set; } = "Letter";
|
||||
[JsonConverter(typeof(PageSizeConverter))]
|
||||
public PageSize PageSize { get; set; } = "Letter";
|
||||
|
||||
/// <summary>
|
||||
/// Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string,
|
||||
|
||||
43
src/ElectronNET.API/Converter/PageSizeConverter.cs
Normal file
43
src/ElectronNET.API/Converter/PageSizeConverter.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
namespace ElectronNET.Converter;
|
||||
|
||||
public class PageSizeConverter : JsonConverter<PageSize>
|
||||
{
|
||||
public override PageSize ReadJson(JsonReader reader, Type objectType, PageSize existingValue, bool hasExistingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (reader.TokenType == JsonToken.String)
|
||||
{
|
||||
return (string)reader.Value;
|
||||
}
|
||||
else if (reader.TokenType == JsonToken.StartObject)
|
||||
{
|
||||
return serializer.Deserialize<PageSize>(reader);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new JsonSerializationException("Invalid value for PageSize. Expected true, false, or an object.");
|
||||
}
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, PageSize value, JsonSerializer serializer)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
writer.WriteUndefined();
|
||||
}
|
||||
|
||||
var str = (string)value;
|
||||
|
||||
if (str is not null)
|
||||
{
|
||||
writer.WriteValue(str);
|
||||
}
|
||||
else
|
||||
{
|
||||
serializer.Serialize(writer, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user