{"id":28928216,"url":"https://github.com/ktsu-dev/roundtripstringjsonconverter","last_synced_at":"2026-02-16T07:17:56.842Z","repository":{"id":298979592,"uuid":"1001392039","full_name":"ktsu-dev/RoundTripStringJsonConverter","owner":"ktsu-dev","description":null,"archived":false,"fork":false,"pushed_at":"2026-02-14T01:51:25.000Z","size":681,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-14T08:44:55.481Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/ktsu-dev.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS.md","dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":"COPYRIGHT.md","agents":null,"dco":null,"cla":null}},"created_at":"2025-06-13T09:51:19.000Z","updated_at":"2026-02-14T01:49:57.000Z","dependencies_parsed_at":"2025-07-22T13:18:12.946Z","dependency_job_id":"1ce92867-98c9-47f5-8921-a889e53f5b9d","html_url":"https://github.com/ktsu-dev/RoundTripStringJsonConverter","commit_stats":null,"previous_names":["ktsu-dev/roundtripstringjsonconverter"],"tags_count":19,"template":false,"template_full_name":null,"purl":"pkg:github/ktsu-dev/RoundTripStringJsonConverter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ktsu-dev%2FRoundTripStringJsonConverter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ktsu-dev%2FRoundTripStringJsonConverter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ktsu-dev%2FRoundTripStringJsonConverter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ktsu-dev%2FRoundTripStringJsonConverter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ktsu-dev","download_url":"https://codeload.github.com/ktsu-dev/RoundTripStringJsonConverter/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ktsu-dev%2FRoundTripStringJsonConverter/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29502934,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-16T05:57:17.024Z","status":"ssl_error","status_checked_at":"2026-02-16T05:56:49.929Z","response_time":115,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":[],"created_at":"2025-06-22T14:12:30.077Z","updated_at":"2026-02-16T07:17:56.822Z","avatar_url":"https://github.com/ktsu-dev.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ktsu.RoundTripStringJsonConverter\n\n\u003e A versatile JSON converter factory that serializes objects using their ToString method and deserializes using FromString, Parse, Create, or Convert methods.\n\n[![License](https://img.shields.io/github/license/ktsu-dev/RoundTripStringJsonConverter)](https://github.com/ktsu-dev/RoundTripStringJsonConverter/blob/main/LICENSE.md)\n[![NuGet](https://img.shields.io/nuget/v/ktsu.RoundTripStringJsonConverter.svg)](https://www.nuget.org/packages/ktsu.RoundTripStringJsonConverter/)\n[![NuGet Downloads](https://img.shields.io/nuget/dt/ktsu.RoundTripStringJsonConverter.svg)](https://www.nuget.org/packages/ktsu.RoundTripStringJsonConverter/)\n[![Build Status](https://github.com/ktsu-dev/RoundTripStringJsonConverter/workflows/build/badge.svg)](https://github.com/ktsu-dev/RoundTripStringJsonConverter/actions)\n[![GitHub Stars](https://img.shields.io/github/stars/ktsu-dev/RoundTripStringJsonConverter?style=social)](https://github.com/ktsu-dev/RoundTripStringJsonConverter/stargazers)\n\n## Introduction\n\n`RoundTripStringJsonConverter` is a powerful JSON converter factory for System.Text.Json that simplifies serialization and deserialization of custom types by leveraging their string representation methods. It automatically detects and uses the most appropriate conversion method from a prioritized list: `FromString`, `Parse`, `Create`, or `Convert`. This approach is particularly useful for value types, strong types, domain objects, and any other types where a string representation makes logical sense.\n\n## Features\n\n- **Multiple Conversion Methods**: Supports `FromString`, `Parse`, `Create`, and `Convert` methods with intelligent priority selection\n- **Automatic Type Detection**: Automatically identifies types with compatible conversion methods\n- **Method Priority System**: Uses `FromString` first, then `Parse`, `Create`, and finally `Convert`\n- **String-Based Serialization**: Converts objects to and from JSON using their string representation\n- **Property Name Support**: Works with both JSON values and property names (dictionary keys)\n- **Reflection Optimization**: Uses cached reflection for improved performance\n- **Generic Method Support**: Handles both generic and non-generic conversion methods\n- **Comprehensive Error Handling**: Graceful handling of invalid types and conversion failures\n\n## Installation\n\n### Package Manager Console\n\n```powershell\nInstall-Package ktsu.RoundTripStringJsonConverter\n```\n\n### .NET CLI\n\n```bash\ndotnet add package ktsu.RoundTripStringJsonConverter\n```\n\n### Package Reference\n\n```xml\n\u003cPackageReference Include=\"ktsu.RoundTripStringJsonConverter\" Version=\"x.y.z\" /\u003e\n```\n\n## Usage Examples\n\n### Basic Example with FromString\n\n```csharp\nusing System.Text.Json;\nusing ktsu.RoundTripStringJsonConverter;\n\n// Configure the converter in your JsonSerializerOptions\nvar options = new JsonSerializerOptions();\noptions.Converters.Add(new RoundTripStringJsonConverterFactory());\n\n// Example custom type with ToString and FromString\npublic class UserId\n{\n    public string Value { get; set; }\n    \n    public static UserId FromString(string value) =\u003e new() { Value = value };\n    \n    public override string ToString() =\u003e Value;\n}\n\n// Serialization\nvar userId = new UserId { Value = \"USER-12345\" };\nstring json = JsonSerializer.Serialize(userId, options);\n// json is now: \"USER-12345\"\n\n// Deserialization\nUserId deserialized = JsonSerializer.Deserialize\u003cUserId\u003e(json, options);\n// deserialized.Value is now: \"USER-12345\"\n```\n\n### Using Different Conversion Methods\n\nThe converter automatically detects and uses the appropriate method based on priority:\n\n```csharp\n// Type with Parse method (common in .NET)\npublic class ProductCode\n{\n    public string Code { get; set; }\n    \n    public static ProductCode Parse(string code) =\u003e new() { Code = code };\n    \n    public override string ToString() =\u003e Code;\n}\n\n// Type with Create method (factory pattern)\npublic class OrderId\n{\n    public string Id { get; set; }\n    \n    public static OrderId Create(string id) =\u003e new() { Id = id };\n    \n    public override string ToString() =\u003e Id;\n}\n\n// Type with Convert method\npublic class CategoryName\n{\n    public string Name { get; set; }\n    \n    public static CategoryName Convert(string name) =\u003e new() { Name = name };\n    \n    public override string ToString() =\u003e Name;\n}\n\n// All types work seamlessly with the same converter\nvar options = new JsonSerializerOptions();\noptions.Converters.Add(new RoundTripStringJsonConverterFactory());\n\nvar product = ProductCode.Parse(\"PROD-ABC\");\nvar order = OrderId.Create(\"ORD-001\");\nvar category = CategoryName.Convert(\"Electronics\");\n\n// All serialize and deserialize correctly\nstring productJson = JsonSerializer.Serialize(product, options);\nstring orderJson = JsonSerializer.Serialize(order, options);\nstring categoryJson = JsonSerializer.Serialize(category, options);\n```\n\n### Method Priority Example\n\nWhen multiple methods are available, the converter uses this priority order:\n\n```csharp\npublic class MultiMethodType\n{\n    public string Value { get; set; }\n    \n    // Highest priority - will be used\n    public static MultiMethodType FromString(string value) =\u003e new() { Value = $\"FromString:{value}\" };\n    \n    // Lower priority - will be ignored\n    public static MultiMethodType Parse(string value) =\u003e new() { Value = $\"Parse:{value}\" };\n    \n    public override string ToString() =\u003e Value;\n}\n\n// FromString method will be used for deserialization\nvar result = JsonSerializer.Deserialize\u003cMultiMethodType\u003e(\"\\\"test\\\"\", options);\n// result.Value will be \"FromString:test\"\n```\n\n### Integration with Other Converters\n\n```csharp\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing ktsu.RoundTripStringJsonConverter;\n\nvar options = new JsonSerializerOptions\n{\n    WriteIndented = true,\n    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,\n    Converters =\n    {\n        new RoundTripStringJsonConverterFactory(),\n        new JsonStringEnumConverter()\n    }\n};\n\n// Now both enum values and custom types with conversion methods will be handled appropriately\n```\n\n## Advanced Usage\n\n### Working with Collections of Custom Types\n\n```csharp\nusing System.Text.Json;\nusing ktsu.RoundTripStringJsonConverter;\n\n// Setup serializer options with the converter\nvar options = new JsonSerializerOptions();\noptions.Converters.Add(new RoundTripStringJsonConverterFactory());\n\n// A collection of custom types\nList\u003cUserId\u003e userIds = new()\n{\n    UserId.FromString(\"USER-001\"),\n    UserId.FromString(\"USER-002\"),\n    UserId.FromString(\"USER-003\")\n};\n\n// Serialize the collection\nstring json = JsonSerializer.Serialize(userIds, options);\n// json is now: [\"USER-001\",\"USER-002\",\"USER-003\"]\n\n// Deserialize back to a collection\nList\u003cUserId\u003e deserializedIds = JsonSerializer.Deserialize\u003cList\u003cUserId\u003e\u003e(json, options);\n```\n\n### Using with Dictionaries as Keys\n\n```csharp\n// Custom types can be used as dictionary keys\nvar userProducts = new Dictionary\u003cUserId, List\u003cProductCode\u003e\u003e\n{\n    { UserId.FromString(\"USER-001\"), [ProductCode.Parse(\"PROD-A\"), ProductCode.Parse(\"PROD-B\")] },\n    { UserId.FromString(\"USER-002\"), [ProductCode.Parse(\"PROD-C\")] }\n};\n\nstring json = JsonSerializer.Serialize(userProducts, options);\n// Serializes as a dictionary with string keys\n\nvar deserialized = JsonSerializer.Deserialize\u003cDictionary\u003cUserId, List\u003cProductCode\u003e\u003e\u003e(json, options);\n// Keys are properly deserialized back to UserId objects\n```\n\n### Complex Domain Objects\n\n```csharp\npublic class Order\n{\n    public OrderId Id { get; set; }\n    public UserId CustomerId { get; set; }\n    public List\u003cProductCode\u003e Products { get; set; }\n    public Dictionary\u003cCategoryName, int\u003e CategoryCounts { get; set; }\n    public DateTime OrderDate { get; set; }\n}\n\n// All custom types are automatically handled\nvar order = new Order\n{\n    Id = OrderId.Create(\"ORD-001\"),\n    CustomerId = UserId.FromString(\"USER-123\"),\n    Products = [ProductCode.Parse(\"PROD-A\"), ProductCode.Parse(\"PROD-B\")],\n    CategoryCounts = new Dictionary\u003cCategoryName, int\u003e\n    {\n        { CategoryName.Convert(\"Electronics\"), 2 }\n    },\n    OrderDate = DateTime.UtcNow\n};\n\nstring json = JsonSerializer.Serialize(order, options);\nOrder deserializedOrder = JsonSerializer.Deserialize\u003cOrder\u003e(json, options);\n```\n\n## API Reference\n\n### RoundTripStringJsonConverterFactory\n\nThe primary class for integrating with System.Text.Json serialization.\n\n#### Methods\n\n| Name | Return Type | Description |\n|------|-------------|-------------|\n| `CanConvert(Type typeToConvert)` | `bool` | Determines if a type can be converted by checking for compatible conversion methods |\n| `CreateConverter(Type typeToConvert, JsonSerializerOptions options)` | `JsonConverter` | Creates a type-specific converter instance |\n\n### Supported Conversion Methods\n\nThe converter looks for static methods in this priority order:\n\n1. **FromString(string)** - Highest priority, commonly used for custom types\n2. **Parse(string)** - Second priority, follows .NET conventions (like int.Parse)\n3. **Create(string)** - Third priority, factory pattern methods\n4. **Convert(string)** - Lowest priority, general conversion methods\n\n### Compatibility Requirements\n\nFor a type to work with RoundTripStringJsonConverter, it must meet these requirements:\n\n1. Have a public static method with one of the supported names (`FromString`, `Parse`, `Create`, or `Convert`)\n2. The method must take a single `string` parameter\n3. The method must return an instance of the declaring type\n4. Override `ToString()` to provide a string representation that can be reversed by the conversion method\n\n#### Valid Method Signatures\n\n```csharp\n// All of these are valid conversion methods:\npublic static MyType FromString(string value) { ... }\npublic static MyType Parse(string value) { ... }\npublic static MyType Create(string value) { ... }\npublic static MyType Convert(string value) { ... }\n```\n\n#### Invalid Method Signatures\n\n```csharp\n// These will NOT work:\npublic MyType FromString(string value) { ... }        // Not static\npublic static MyType FromString(int value) { ... }    // Wrong parameter type\npublic static string FromString(string value) { ... } // Wrong return type\npublic static MyType FromString(string value, IFormatProvider provider) { ... } // Too many parameters\n```\n\n## Performance Considerations\n\n- **Reflection Caching**: Method information is cached for improved performance on repeated conversions\n- **Large Collections**: Tested with collections of 1000+ items\n- **Memory Efficiency**: Minimal memory overhead per conversion\n- **Thread Safety**: The converter factory is thread-safe\n\n## Error Handling\n\nThe converter provides comprehensive error handling:\n\n- **Invalid JSON Types**: Throws `JsonException` for non-string JSON tokens\n- **Conversion Failures**: Propagates exceptions from conversion methods\n- **Missing Methods**: Types without valid conversion methods are ignored\n- **Null Arguments**: Proper `ArgumentNullException` handling\n\n## Migration from ToStringJsonConverter\n\nIf you're migrating from the previous `ToStringJsonConverter`:\n\n1. Update package reference to `ktsu.RoundTripStringJsonConverter`\n2. Update using statements: `using ktsu.RoundTripStringJsonConverter;`\n3. Update converter instantiation: `new RoundTripStringJsonConverterFactory()`\n4. Your existing `FromString` methods will continue to work unchanged\n5. You can now also use `Parse`, `Create`, or `Convert` methods\n\n## Contributing\n\nContributions are welcome! Here's how you can help:\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\nPlease make sure to update tests as appropriate.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fktsu-dev%2Froundtripstringjsonconverter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fktsu-dev%2Froundtripstringjsonconverter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fktsu-dev%2Froundtripstringjsonconverter/lists"}