[英]Convert Ruby hash to Json in C#
我正在尋找幫助,以編寫一種將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"}]}
通過逐步替換其他字符串元素,我發現了一個骯臟但可行的替代方法。 它運作完美。
// 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.