All Articles

C#

Newtonsoft Nullable Json Property Read and Write

public class Model
{
   // required property 지정할 방법 고민할 것
    private int? data1;
    private int? data2;

    public Model(int? data1, int? data2)
    {
        this.Data1 = data1;
        this.Data2 = data2;
    }

    public int? Data1
    {
        // 기본값 할당이 필요할때 어떻게 할지
        get => data1;
        set => data1 = value;
    }

    public int? Data2
    {
        get => data2;
        set => data2 = value;
    }
}

public class Program
{

    public static T ReadFile<T>(string filename) where T : class
    {
        if (File.Exists(filename))
        {
            var json = File.ReadAllText(filename);
            if (!string.IsNullOrEmpty(json))
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
        }
        return null;
    }

    public static async Task WriteFileAsync<T>(string fullFileName, T jsonObject)
    {
        var directoryName = Path.GetDirectoryName(fullFileName);
        if (directoryName != null && !string.IsNullOrEmpty(directoryName))
        {
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
        }
        using (var file = File.CreateText(fullFileName))
        {
            using (var writer = new JsonTextWriter(file))
            {
                string json = JsonConvert.SerializeObject(jsonObject, Formatting.Indented, 
                    new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore } );
                await writer.WriteRawAsync(json);
            }
        }
    }

    private async static void Run()
    {
        var model = ReadFile<Model>("test.json");
        Console.WriteLine(model.Data1);
        Console.WriteLine(model.Data2);
        await WriteFileAsync("test.json", model);
        var writtenModel = ReadFile<Model>("test.json");
        Console.WriteLine(writtenModel.Data1);
        Console.WriteLine(writtenModel.Data2);
    }

    static void Main(string[] args)
    {
        Run();
        Thread.Sleep(100);
    }
}