以多行显示 JSON 文件的内容,而不是一长行
在 Unity 中,我使用 JSON 文件保存我的游戏.当我在 Visual Studio 中打开文件时,它会在一行中显示整个内容及其所有变量.这是我的 JSON 文件的一小部分:
In Unity, I save my game using JSON files. When I open the file in Visual Studio, it shows the whole content with all its variables in one single line. Here is a small part of my JSON file:
// JSON before my copy / paste-trick (see below)
{"lastTicketDate":"04.13.2020","lastTicket":{"Id":2,"Type":0,"Fortune":"Fortune02","Author":"Me!!!\r","ShinyEffect":0,"BeenDrawn":true},"firstStart":false,"tickets":[{"Id":1,"Type":0,"Fortune":"Fortune01","Author":
// (...)
这不是很可读.如何设置 Visual Studio 以正确显示内容,每个变量在单独的行中,如下所示:
This is not very readable. How can I set up Visual Studio to show me the content properly, each variable in a separate line, like this:
// JSON after my copy / paste trick (see below)
{
"lastTicketDate": "04.13.2020",
"lastTicket": {
"Id": 2,
"Type": 0,
"Fortune": "Fortune02",
"Author": "Me!!!\r",
"ShinyEffect": 0,
"BeenDrawn": true
},
"firstStart": false,
"tickets": [
{
"Id": 1,
"Type": 0,
"Fortune": "Fortune01",
"Author": "Me!!!\r",
"ShinyEffect": 0,
"BeenDrawn": false
},
// (...)
目前,我是这样做的:双击一个词 -> 复制它 (Ctrl+c) -> 将其粘贴回 (Ctrl+v) -> 现在格式更改为所需的版本.
Currently, I do it like this: Double-click on one word -> copy it (Ctrl+c) -> paste it back in (Ctrl+v) -> now the format changed to the desired version.
我该如何解决这个问题,正确的方法是什么?
How do I fix this issue, what is the correct way to do it?
现在,当你保存你的 json 时,它会以最小尺寸的格式输出,这是无缩进的,这就是为什么一切都如此压缩.
Right now when saving you output your json in the smallest size format, which is unindented, so that is why everything is so compressed.
您可以改为更改 json 序列化程序以输出已识别的格式.
You can instead, change your json serializer to output an idented format.
例如使用内置 json util 时;
e.g. when using the builtin json util;
https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html
var indented = JsonUtility.ToJson(this, true);
编辑
由于这个答案随着时间的推移受到了一些关注,以下是在其他流行库中输出缩进 JSON 的方法:
Since this answer got some traction over time, here's how to output indented JSON in other popular libraries:
JsonConvert.SerializeObject(json, Formatting.Indented);
JsonSerializer.Serialize(json, new JsonSerializerOptions { WriteIndented = true })