Skip to content

Instantly share code, notes, and snippets.

@kezzyhko
Last active October 3, 2024 07:29
Show Gist options
  • Select an option

  • Save kezzyhko/6069b6484b3680a458eb82050179e6c4 to your computer and use it in GitHub Desktop.

Select an option

Save kezzyhko/6069b6484b3680a458eb82050179e6c4 to your computer and use it in GitHub Desktop.
Class for modifying Json files using DataContract (+ an example for Unity's manifest file)
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
public class JsonFile<T> : IDisposable, IAsyncDisposable
{
private static readonly DataContractJsonSerializer Serializer = new(typeof(T), new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true,
});
private readonly FileStream _stream;
private T _content;
private bool _isDisposed = false;
public T Content
{
get
{
CheckDisposed();
return _content;
}
set
{
CheckDisposed();
_content = value;
}
}
private void CheckDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
public JsonFile(string path)
{
_stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
Content = (T)Serializer.ReadObject(_stream);
}
public void Dispose()
{
if (_isDisposed)
{
return;
}
Serializer.WriteObject(_stream, _content);
_stream?.Dispose();
_isDisposed = true;
}
public async ValueTask DisposeAsync()
{
if (_isDisposed)
{
return;
}
Serializer.WriteObject(_stream, _content);
await _stream.DisposeAsync();
_isDisposed = true;
}
}
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
[DataContract]
[SuppressMessage("ReSharper", "InconsistentNaming")]
public record Manifest : IExtensibleDataObject
{
[DataMember] public Dictionary<string, string> dependencies { get; set; }
[DataMember] public List<ScopedRegistry> scopedRegistries { get; set; }
public ExtensionDataObject ExtensionData { get; set; }
}
[DataContract]
[SuppressMessage("ReSharper", "InconsistentNaming")]
public record ScopedRegistry : IExtensibleDataObject
{
[DataMember] public string name { get; set; }
[DataMember] public string url { get; set; }
[DataMember] public List<string> scopes { get; set; }
public ExtensionDataObject ExtensionData { get; set; }
}
using System;
using UnityEditor;
public static class Installer
{
[InitializeOnLoadMethod]
private static void Init()
{
using var manifest = new JsonFile<Manifest>("Packages/manifest.json");
manifest.Content.scopedRegistries.Add("com.example.test");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment