81 lines
2.8 KiB
C#
81 lines
2.8 KiB
C#
using System;
|
|
using System.Globalization;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Converters;
|
|
|
|
namespace MelonVPNCore
|
|
{
|
|
// I hate overhead but this code is just nice xD
|
|
|
|
// Base json class with type property FromJson and ToJson methods
|
|
public class JsonBase
|
|
{
|
|
[JsonProperty("type")]
|
|
public string Type { get; set; }
|
|
|
|
// Convert from json string to WSJson class
|
|
public static JsonBase FromJson(string json) => JsonConvert.DeserializeObject<JsonBase>(json, Converter.Settings);
|
|
|
|
// Convert any class into a json string
|
|
public string ToJson() => JsonConvert.SerializeObject(this, Converter.Settings);
|
|
|
|
// Converter with settings
|
|
internal static class Converter
|
|
{
|
|
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
|
|
{
|
|
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
|
|
DateParseHandling = DateParseHandling.None,
|
|
Converters =
|
|
{
|
|
new IsoDateTimeConverter{DateTimeStyles=DateTimeStyles.AssumeUniversal }
|
|
}
|
|
};
|
|
}
|
|
}
|
|
|
|
// Base class for custom json with a type argument
|
|
public class JsonBase<T> : JsonBase
|
|
{
|
|
// Convert from json string to T class
|
|
public static new T FromJson(string json) => JsonConvert.DeserializeObject<T>(json, Converter.Settings);
|
|
|
|
// Used to convert json property into type long
|
|
internal class ParseStringConverter : JsonConverter
|
|
{
|
|
public override bool CanConvert(Type objectType) { return objectType == typeof(long) || objectType == typeof(long); }
|
|
|
|
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
|
{
|
|
if (reader.TokenType == JsonToken.Null) return null;
|
|
var value = serializer.Deserialize<string>(reader);
|
|
if (long.TryParse(value, out long l)) return l;
|
|
throw new Exception("Cannot unmarshal type long");
|
|
}
|
|
|
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
|
{
|
|
if (value == null)
|
|
{
|
|
serializer.Serialize(writer, null);
|
|
return;
|
|
}
|
|
var v = (long)value;
|
|
serializer.Serialize(writer, v.ToString());
|
|
return;
|
|
}
|
|
|
|
public static readonly ParseStringConverter Singleton = new ParseStringConverter();
|
|
}
|
|
}
|
|
|
|
// Class for the daemon config
|
|
public class DaemonConfig : JsonBase<DaemonConfig>
|
|
{
|
|
public DaemonConfig() => Type = "DaemonConfig";
|
|
|
|
[JsonProperty("restart")]
|
|
public bool ShouldRestart { get; set; }
|
|
}
|
|
}
|