如何在C#中实现Ruby Hash转JSON的方法?
如何在C#中实现Ruby Hash转标准JSON?
嘿,我懂你想要的效果——就像Ruby里的to_json那样,把Ruby风格的Hash字符串一键转成标准JSON对吧?刚好我有几个实用的方案可以分享给你:
方案一:轻量正则替换(适合简单场景)
如果你的Ruby Hash结构不复杂,没有太多特殊字符或深层嵌套,用正则做语法替换就能快速搞定。核心是把Ruby Hash的语法转换成JSON兼容格式:
- 把符号键(比如
:key)替换成带双引号的JSON键("key") - 把Ruby的键值分隔符
=>替换成JSON的: - 处理单引号转双引号的问题
以下是完整的C#代码示例:
using System; using System.Text.RegularExpressions; using System.Text.Json; public class RubyHashConverter { public static string ConvertRubyHashToJson(string rubyHashStr) { // 替换符号键:把 :key 格式转为 "key" string processed = Regex.Replace(rubyHashStr, @"(\w+):", match => $"\"{match.Groups[1].Value}\":"); // 替换Ruby键值分隔符 => 为JSON的 : processed = processed.Replace("=>", ":"); // 把单引号统一转成双引号(如果Ruby字符串用了单引号的话) processed = processed.Replace("'", "\""); // 确保数组内的Hash括号格式正确 processed = Regex.Replace(processed, @"\{(\s*""[^""]+"":)", match => $"{{{match.Groups[1].Value}"); // 验证并格式化JSON(可选,让输出更美观) try { var jsonObj = JsonSerializer.Deserialize<object>(processed); return JsonSerializer.Serialize(jsonObj, new JsonSerializerOptions { WriteIndented = true }); } catch (Exception ex) { throw new InvalidOperationException("转换失败,输入的Ruby Hash格式可能不规范", ex); } } } // 使用示例 string rubyHash = @"{""section""=>""Gar"", ""code""=>2, ""collections""=>[{:key=>""emotion"", :value=>""Emotion""}], ""batch""=>""M""}"; string jsonResult = RubyHashConverter.ConvertRubyHashToJson(rubyHash); Console.WriteLine(jsonResult);
注意:如果你的Ruby Hash包含复杂嵌套、特殊字符(比如键里带空格或转义字符),这个方案可能会失效,这时可以试试下面的专业解析方案。
方案二:用IronRuby解析(适合复杂场景)
如果需要处理更复杂的Ruby Hash结构(比如多层嵌套数组、特殊语法),可以用IronRuby库直接解析Ruby代码,再转换成C#对象后序列化JSON。
首先需要安装IronRuby的NuGet包:
Install-Package IronRuby
然后是代码示例:
using IronRuby; using System.Text.Json; public class RubyHashConverter { public static string ConvertWithIronRuby(string rubyHashStr) { var rubyEngine = Ruby.CreateEngine(); // 执行Ruby代码,直接获取Hash对象 var rubyHashObj = rubyEngine.Execute($"return {rubyHashStr}"); // 把Ruby Hash转换成C#可识别的动态对象 dynamic csharpObj = rubyEngine.Runtime.Execute("lambda { |obj| obj.to_hash }").Invoke(rubyHashObj); // 序列化成标准JSON return JsonSerializer.Serialize(csharpObj, new JsonSerializerOptions { WriteIndented = true }); } } // 使用示例 string rubyHash = @"{""section""=>""Gar"", ""code""=>2, ""collections""=>[{:key=>""emotion"", :value=>""Emotion""}], ""batch""=>""M""}"; string jsonResult = RubyHashConverter.ConvertWithIronRuby(rubyHash); Console.WriteLine(jsonResult);
这个方案的优势是能完美兼容Ruby的各种语法细节,缺点是需要引入第三方库,会增加项目体积。
内容的提问来源于stack exchange,提问作者Bastien Vandamme
相关产品推荐
相关产品推荐

