C# json formatting a save

At the moment my json files are ~20% longer than my xml files for the same data.

Theres a couple of reasons, but one I would like to fix is the formatting to be more readable / cleaner, ATM everything goes onto a separate line like so (for a vector3/SerializableVector3)

“pos”: {
“x”: 111,
“y”: 39.56,
“z”: 84
},

is it possible to override the way it saves json per data type eg for this I would like the much nicer
“pos”: { “x”:111, “y”:39.56, “z”:84 },

or an array
“abilities”: [
7,
0,
0,
0,
3,
0,
0
],

becomes eg

“abilities”: [7,0,0,0,3,0,0],

Is such a thing easily possible? (i.e. without writing my own parser)
I sort of what to do the same thing as overriding eg ToString()
cheers zed

Not strictly unity related sorry.

You don’t mention what library/API you’re using for JSON. I assume you’re using Unity’s built-in JsonUtility, right?

If so, by default Unity will format your JSON to minimize space: https://docs.unity3d.com/2019.3/Documentation/ScriptReference/JsonUtility.ToJson.html

It will only add line breaks and format your code if you pass true as the value for the “prettyPrint” optional parameter. It’s not very flexible tbh, you either get everything crammed in a small space or you don’t. It’s not possible to fine-tune formatting as far as I know.

2 Likes

Like arkano said we don’t know how you’re currently serializing your data. Most people probably use Newtonsoft’s Json.net library. I’m not sure how well it supports individual formatting. My own parser does have an inline flag for every object \ array node. The Unity specific extension file does use this flag for vectors, colors, quaternions and matrices.

Though, this parser is not a classical object mapper but instead maps to its own json primitive types.

1 Like

Sorry guys, I should of been more specific. Yes the inbuilt one.
I’ll look at that extension file Bunny83
I’ll study this a bit more.