如何在 IntelliJ/Android Studio 中格式化粘贴的 JSON

我经常需要使用一个文本编辑器,而编写代码粘贴随机笔记,但特别是 JSON 响应,其中我格式化他们使用插件(为崇高)。

我最近听说了 IntelliJ/Android Studio 中的“草稿文件”功能,它完全满足我的需要——除了我不能让它格式化我粘贴的 JSON。

我怎样才能使 Android Studio 格式化 JSON 在一个抓取缓冲文件?

108290 次浏览

If you run the latest version I'd create a new Scratch File of type JSON. It's really easy, e.g. hit double shift, then search for new scratch file, select JSON as the language, paste your snippet and then use the shortcut that you usually use for formatting any file in intelliJ.

You are asking about two seperate things: scratch files and scratch buffers.

When you create a scratch file in IntelliJ you can choose the type of the file (e.g. JSON) that you want to create. Based on file's type, IntelliJ provides code formatting (use Code->Reformat code).

However, scratch buffers are just simple .txt files and the only formatting that can be used is the one associated to .txt format. So, if you put JSON into scratch buffer it won't get formatted with JSON type formatter.

I would encourage you to use scratch files instead of scratch buffers if you want JSON formatting.

More information can be found at IntelliJ's official page https://www.jetbrains.com/help/idea/2016.2/scratches.html.

I highlight the code and run Command Option L (a short-cut for the Code->Reformat Code menu).

On Windows use Ctrl Alt L.

Note that this only works if the code is well-formed JSON (clear any red squiggles).

choose from the menu : code -> reformat code

hotkey On Windows -:

CTRL + Alt + L

Important note- if you have sensitive information in your JSON- NEVER use online tools to parse or beautify it. because this will compromise your organization's and customer's information

There is a plugin Save Actions that does auto-formatting (also of JSON) every time when I save the file:

select Android Studio > Preferences > Plugins

check Martketplace tab and search for Save Actions (it has a red square-ish icon) and press Install next to it.

At this point you will need to restart your android studio, and then you can enable "Reformat on save" by:

select Android Studio > Preferences > Other Settings > Save actions, in there, select:

✅ General > activate save actions on save

✅ Formatting actions > Reformat File