{"id":13629611,"url":"https://github.com/hermanussen/JsonByExampleGenerator","last_synced_at":"2025-04-17T09:35:07.412Z","repository":{"id":46237780,"uuid":"328784609","full_name":"hermanussen/JsonByExampleGenerator","owner":"hermanussen","description":"Generate classes based on example json files in your project. Uses a C# 9 source generator.","archived":false,"fork":false,"pushed_at":"2023-01-10T09:36:30.000Z","size":682,"stargazers_count":78,"open_issues_count":1,"forks_count":9,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-08-01T22:44:01.584Z","etag":null,"topics":["csharp-sourcegenerator","json"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hermanussen.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-01-11T20:34:00.000Z","updated_at":"2024-08-01T15:42:04.000Z","dependencies_parsed_at":"2023-02-08T18:02:07.555Z","dependency_job_id":null,"html_url":"https://github.com/hermanussen/JsonByExampleGenerator","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermanussen%2FJsonByExampleGenerator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermanussen%2FJsonByExampleGenerator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermanussen%2FJsonByExampleGenerator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermanussen%2FJsonByExampleGenerator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hermanussen","download_url":"https://codeload.github.com/hermanussen/JsonByExampleGenerator/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223751278,"owners_count":17196603,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp-sourcegenerator","json"],"created_at":"2024-08-01T22:01:14.811Z","updated_at":"2024-11-08T20:31:23.725Z","avatar_url":"https://github.com/hermanussen.png","language":"C#","readme":"# JsonByExampleGenerator\n\n![publish to nuget](https://github.com/hermanussen/JsonByExampleGenerator/workflows/publish%20to%20nuget/badge.svg) [![Nuget](https://img.shields.io/nuget/v/JsonByExampleGenerator)](https://www.nuget.org/packages/JsonByExampleGenerator/) [![Nuget](https://img.shields.io/nuget/dt/JsonByExampleGenerator?label=nuget%20downloads)](https://www.nuget.org/packages/JsonByExampleGenerator/) [![Twitter URL](https://img.shields.io/twitter/url?style=social\u0026url=https%3A%2F%2Ftwitter.com%2Fknifecore%2F)](https://twitter.com/knifecore)\n\nGenerate classes based on example json files in your project. Uses a C# 9 source generator.\n\n# Installation\n\n1. Install the NuGet package in your project. Run the following command in the NuGet package manager console\n```\nInstall-Package JsonByExampleGenerator\n```\nor using the .NET cli\n```\ndotnet add package JsonByExampleGenerator\n```\n2. Ensure the json files that you want to use as examples are added as `AdditionalFiles` in your `.csproj` file. E.g.:\n```xml\n\u003cItemGroup\u003e\n  \u003c!-- Files must have the .json extension --\u003e\n  \u003cAdditionalFiles Include=\"products.json\" /\u003e\n\u003c/ItemGroup\u003e\n```\n3. You can now use the generated classes in your code. Add a using statement for `[your_dll_name_without_extension].Json.[json_filename_csharp_friendly]`. E.g.:\n```csharp\n// For /mock_files/products.json\nusing MyCompany.MyProject.Json.Products;\n```\nIntellisense should help you out when adding a using statement for this.\n\n# Example usage\n\n## Use a json file to generate classes\n\n[![Json configuration feature example](Media/jsonbyexample_simple.gif)]\n\nGiven the following `products.json` file:\n```json\n[\n  {\n    \"id\": 12,\n    \"name\": \"Example product\",\n    \"colorVariants\": [\n      {\n        \"variantId\": 12,\n        \"color\": \"Red\"\n      },\n      {\n        \"variantId\": 10,\n        \"color\": \"Green\"\n      }\n    ]\n  }\n]\n```\n\nYou can then use the generated code as follows:\n\n```csharp\nvar product = new Product()\n    {\n        Id = 16,\n        Name = \"Violin\"\n        ColorVariants = new List\u003cColorVariant\u003e()\n        {\n            new ColorVariant()\n            {\n                VariantId = 17,\n                Color = \"Blue\"\n            }\n        }\n    };\n```\n\n## Use a constant string with json data in code to generate classes\n\nGiven the following string constant in your code:\n```csharp\n[JsonExample(\"Animal\")]\nprivate const string AnimalJsonInCode = @\"\n{\n    \"\"name\"\" : \"\"Spider\"\",\n    \"\"legs\"\" : 8\n}\";\n```\n\nYou can then use the generated code as follows:\n\n```csharp\nvar spider = new Animal()\n    {\n        Name = \"Spider\",\n        Legs = 8\n    };\n```\n\n## Get json configuration without the need for magic strings\n\n[![Json configuration feature example](Media/jsonbyexample_config.gif)]\n\nIf you are using json configuration providers, you can do the following:\n\n1. Ensure that the following NuGet packages are installed: `Microsoft.Extensions.Configuration.Json` and `Microsoft.Extensions.Configuration.Binder`.\n2. Ensure that the `appsettings.json` (or any other configuration files) are included in the compilation as `AdditionalFiles` (as mentioned in the installation instructions). A typical example from your project file would look like this:\n```xml\n\u003cAdditionalFiles Include=\"appsettings.json\"\u003e\n  \u003cCopyToOutputDirectory\u003ePreserveNewest\u003c/CopyToOutputDirectory\u003e\n\u003c/AdditionalFiles\u003e\n``` \n\nNow, given the following configuration file:\n```json\n{\n  \"AppSettings\": {\n    \"exampleSetting\": \"example value\"\n  }\n}\n```\n\nYou would normally do this:\n```csharp\n// outputs \"example value\"\nconfig.GetSection(\"Something\").GetSection(\"SomeValue\").Value\n```\nBut now, you can do this:\n```csharp\n// outputs \"example value\"\nAppsetting.FromConfig(config).Something.SomeValue\n```\n\n## Use your own Scriban template instead of the default one\n\nIf you have specific needs for the generated code, you can easily create a [Scriban](https://github.com/scriban/scriban) template to replace the default one. All you have to do is:\n1. Create a file with the same name as your example json file, but with the extension `.sbntxt` instead of `.json`.\n2. Ensure that the file is included in the `AdditionalFiles` for your project (the same way that you include your json files).\n3. Copy the contents of the [default template](JsonByExampleGenerator.Generator/JsonByExampleTemplate.sbntxt), paste them in the file and save.\n4. Change the template in any way you want, and you should observe the changes when you build your project.\n\nIf you want to change the code generation for all json files in a folder or the whole project (instead of adjusting for a single json file), you can use the following alternative step instead of step 1:\n1. Create a file named `JsonByExampleTemplate.sbntxt` and place it in the folder where your json files are. If the template file is not there, the generator will go up one parent folder until it finds one (but will not go past the project root). Don't forget the other steps defined above.\n\nThere is also a template that is used to generate some global project code. If you want to change that, you can create a file named `OnlyOnceTemplate.sbntxt` in the root of your project. Make sure it is included in `AdditionalFiles`. Copy the contents of the default version [from here](JsonByExampleGenerator.Generator/OnlyOnceTemplate.sbntxt).\n\n## Manually change the type or name of properties\n\nSometimes you may not like the name of the property or the type that is used. For example, if you want a `long` instead of an `int`. The generator has to guess, based on example data. And that may not always have the desired result.\n\nYou can fix this by specifying the property exactly how you want it in a partial class. Example:\n\nGiven the following `products.json` file:\n```json\n[\n  {\n    \"id\": 12,\n    \"name\": \"Example product\"\n  }\n]\n```\n\nYou can specify this partial class:\n\n```csharp\nnamespace MyNs.Json.Products\n{\n  public partial class Product\n  {\n    // Based on the value of the name in the attribute, the generator knows not to generate this property\n    [DataMember(Name = \"id\")]\n    public long Id { get; set; } // Generates 'int' by default\n  }\n}\n```\n\n## Manually change the name of generated types\n\nThe generator automatically attempts to determine names for generated types. For example, if a json property is named \"products\", the model that will be used is `Product`. If you don't like that, you can easily change it by using the `JsonRenamedFrom` attribute.\n\nGiven the following `products.json` file:\n```json\n[\n  {\n    \"id\": 12,\n    \"name\": \"Example product\"\n  }\n]\n```\n\nBy default, it will render something like this:\n```csharp\nnamespace MyNs.Json.Products\n{\n  [DataContract]\n  public partial class Product\n  {\n    // ...\n  }\n}\n```\n\nYou can specify this partial class:\n\n```csharp\nusing MyNs.Json;\n\nnamespace MyNs.Json.Products\n{\n  [JsonRenamedFrom(\"Product\")]\n  public partial class Asset\n  {\n  }\n}\n```\n\nThe generator will respect the new name and change it in all generated code.\n\n## Manually change the namespace for generated code\n\nBy default, the generator will generate all code under `[your_dll_name_without_extension].Json.[json_filename_csharp_friendly]`. But if you want, you can change this by providing an assembly level attribute. For example:\n```csharp\nusing MyNs.Json;\n\n[assembly:JsonRenameNamespace(\"MyNs.Json.Something\", \"MyNs.Something.Else\")]\n```","funding_links":[],"categories":["Source Generators","Do not want to test 112 ( old ISourceGenerator )"],"sub_categories":["Serialization","1. [ThisAssembly](https://ignatandrei.github.io/RSCG_Examples/v2/docs/ThisAssembly) , in the [EnhancementProject](https://ignatandrei.github.io/RSCG_Examples/v2/docs/rscg-examples#enhancementproject) category"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhermanussen%2FJsonByExampleGenerator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhermanussen%2FJsonByExampleGenerator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhermanussen%2FJsonByExampleGenerator/lists"}