Home > Mobile >  How to generate code for a json file (with its data) at compile time?
How to generate code for a json file (with its data) at compile time?

Time:02-25

Imagine, there is a large json file with data. These data will never change for that version of the software. This is my file data.json:

{
    coordinates: [
        {x: 1, y: 2},
        {x: 2, y: 23},
        {x: 213, y: 82},
        {x: 41, y: 22},
        // ....
    ]
}

When we want to use that file, we could deserialize its data during runtime.

But that's kind of wasted time because we'd do this work on every application start (opening the file, reading the content, deserializing it, ...) instead of just once.

Is it somehow possible to use a "code generator" to do this at compile time, or even before? "before" means: You can already save a .settings file in VS and it modifies the App.config file automatically then. Would it be possible to generate a .cs file if the json file as soon as someone saves it or builds the project?

This is what I expect as a result: A file Data.cs:

public class Data{
    public Coordinate[] Coordinates {
        get => new Coordinate[]{
            new (1,2),
            new (2,23),
            new (213,82),
            new (41,22),
        };
    }
}

CodePudding user response:

There is an online tools that converts JSON to C# called quicktype.io, which you can get packaged as a Visual Studio Code Extension. Not only does it convert JSON to C#, but also to TypeScript, Python, Go, Ruby, Java, Swift, Rust, Kotlin, C , Flow, Objective-C, JavaScript, Elm, and JSON Schema.

It's not exactly what you are asking for, but achieves the objective of statically translating JSON to code.

CodePudding user response:

Json file usually keeps a json version of data. If you want to have data in a compile time you will have to keep it in .cs file as a string constant. But I am not sure that will save time significantly


//ConstCoordianates.cs
public static class ConstCoordianates
{

public static ReadOnlyCollection<Coordinate> coordinates { get; set; } = 
new ReadOnlyCollection<Coordinate>(JsonConvert.DeserializeObject<Data>
(Coordinates).Coordinates);

    public const string Coordinates = @"{
    ""coordinates"": [{
            ""x"": 1,
            ""y"": 2
        },
        {
            ""x"": 2,
            ""y"": 3
        }
    ]
    }";
}

classes

public partial class Data
{
    [JsonProperty("coordinates")]
    public List<Coordinate> Coordinates { get; set; }
}

public partial class Coordinate
{
    [JsonProperty("x")]
    public long X { get; set; }

    [JsonProperty("y")]
    public long Y { get; set; }
}
  • Related