代码改变世界

格式化 打印Json 串

2022-08-18 10:25  qgbo  阅读(60)  评论(0)    收藏  举报
using Newtonsoft.Json.Linq;

Console.WriteLine("Hello, World!");

var str = "{\"data\":{\"event\":\"$transitions.onSuccess22\",\"toState\":\"abc\",\"toParams\":{\"#\":null},\"fromState\":\"a.login\",\"fromParams\":{\"#\":null}},\"location\":\"http://abc/login\",\"context\":{\"uuid\":\"16606189728409564275\",\"user\":\"DKX4AX1\"},\"browser\":{\"userAgent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36\",\"platform\":\"Win32\",\"vendor\":\"Google Inc.\",\"language\":\"zh-CN\",\"cookieEnabled\":true,\"connection\":{}}}";

var m = JObject.Parse(str);
paser(m,-2);

void paser(JToken token, int depth)
{
    depth += 2;
    var s = token as JObject;
    if(s is not null)
        foreach (var item in s)
        {
            var desent = "".PadLeft(depth);
            if (item.Value.Any())
            {
                Console.WriteLine($"{desent}{item.Key}:");
                paser(item.Value, depth);
            }
                
            else
            { 
                Console.WriteLine($"{desent}{item.Key}:{item.Value}");
            }  
        }
}