【问题标题】:Convert Ruby hash to Json in C#在 C# 中将 Ruby 哈希转换为 Json
【发布时间】:2018-01-12 09:20:18
【问题描述】:

我正在寻求帮助,以编写一种在 C# 中将 Ruby 哈希转换为 Json 的方法。

仅供参考,Ruby 哈希是这样的:

{"tiger"=>3, "lion"=>2, "dog"=>2, "cat"=>3}

但也可以包含这样的数组

{"section"=>"Gar", "code"=>2, "collections"=>"[{:key=>\"emotion\", :value=>\"Emotion\"}]", "batch"=>"M"}

我知道使用 Ruby 中的 to_json 指令将 Ruby 哈希转换为 Json 非常容易,但我正在寻找 C# 中的类似指令(如果存在)。

换句话说,我收到了这种格式的字符串:

{"section"=>"Gar", "code"=>2, "collections"=>"[{:key=>\"emotion\", :value=>\"Emotion\"}]", "batch"=>"M"}

我想要这个

{"section": "Gar", "code": 2, "batch": "M", "collections": [{"key": "emotion", "value": "Emotion"}]}

【问题讨论】:

  • 您的问题不清楚。当您说“Ruby 哈希”时,您的意思可能是包含 Ruby 哈希语法的字符串吗?
  • 是的,但在 Ruby 中它并不是真正的字符串......在数据库中它被保存为字符串(hstore)以外的其他东西,所以我只是尽量避免使用“字符串”这个词来避免混乱。似乎它实际上造成了混乱。抱歉,我不是 Ruby 开发人员。
  • 您没有在问题中提及数据库。如果您可以备份一下,那将很有帮助。这些数据来自哪里?您的程序如何接收或检索它?
  • 与开发人员交谈并告诉他们您没有使用 Ruby,因此您无法解析 Ruby,并要求他们为您提供一种获取 JSON 的方法。其他语言不知道如何解析 Ruby 是有原因的:我们已经拥有像 JSON 这样的优秀、文档齐全、标准化的数据序列化格式,而且每个主要平台都知道如何生成和解析这些数据。
  • 我猜简单替换是行不通的,因为这些符号可能出现在值中。我同意其他人的观点 - 从 web api 返回 ruby​​ 哈希是一个非常糟糕的主意。

标签: c# json ruby


【解决方案1】:

通过逐步将我的字符串元素替换为其他人,我找到了一个肮脏但可行的替代方案。效果很好。

// Define other methods and classes here
public string ToJson(string hash)
{
    hash = Regex.Replace(hash, @":(\w+)=>", @"""$1"": ");
    hash = Regex.Replace(hash, @"\\""", @"""");
    hash = Regex.Replace(hash, @"\\\\", @"");
    hash = Regex.Replace(hash, @"=>", @": ");
    hash = Regex.Replace(hash, @"""\[", @"[");
    hash = Regex.Replace(hash, @"\]""", @"]");
    hash = Regex.Replace(hash, @"""\{", @"{");
    hash = Regex.Replace(hash, @"\}""", @"}");
    hash = Regex.Replace(hash, @"NULL", @"null");
    hash = $"{{{hash}}}";
    //JObject jObject = (JObject)JsonConvert.DeserializeObject(hash);
    return hash;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2013-11-13
    • 1970-01-01
    • 2013-07-06
    相关资源
    最近更新 更多