如何将AWS角色策略文档中的不可读字符转换为可读格式?
解决AWS IAM GetRolePolicyAsync返回URL编码策略文档的问题
要将返回的URL编码策略文档转换为可读的格式化JSON,只需完成两步操作:URL解码和JSON格式化,以下是具体实现方案:
核心代码实现
使用System.Text.Json(.NET Core 3.0+ 内置)
using System; using System.Net; using System.Text.Json; var inlinePolicyDetails = iamClient.GetRolePolicyAsync(new GetRolePolicyRequest { RoleName = "xyzRole", PolicyName = "xyzPolicy" }).GetAwaiter().GetResult(); // 1. 对URL编码的PolicyDocument进行解码 var decodedRawJson = WebUtility.UrlDecode(inlinePolicyDetails.PolicyDocument); // 2. 格式化JSON字符串,提升可读性 var serializeOptions = new JsonSerializerOptions { WriteIndented = true }; var formattedPolicyJson = JsonSerializer.Serialize( JsonSerializer.Deserialize<object>(decodedRawJson), serializeOptions ); Console.WriteLine(formattedPolicyJson);
使用Newtonsoft.Json(第三方库)
如果项目中已经使用Newtonsoft.Json,也可以用以下方式实现:
using System; using System.Net; using Newtonsoft.Json; var inlinePolicyDetails = iamClient.GetRolePolicyAsync(new GetRolePolicyRequest { RoleName = "xyzRole", PolicyName = "xyzPolicy" }).GetAwaiter().GetResult(); var decodedRawJson = WebUtility.UrlDecode(inlinePolicyDetails.PolicyDocument); var formattedPolicyJson = JsonConvert.SerializeObject( JsonConvert.DeserializeObject(decodedRawJson), Formatting.Indented ); Console.WriteLine(formattedPolicyJson);
效果说明
执行上述代码后,原本的URL编码字符串会被转换为你期望的格式化JSON:
{ "Version": "2012-10-17", "Statement": [ { "Action": [ "XYZ:ABCD" ], "Effect": "Allow", "Resource": "*" } ] }
内容的提问来源于stack exchange,提问作者Shankar S
相关产品推荐
相关产品推荐

