• Stars
    star
    328
  • Rank 128,352 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 5 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Converters of common Unity types for Newtonsoft.Json. Goes hand in hand with jilleJr/Newtonsoft.Json-for-Unity

Unity Converters for Newtonsoft.Json

openupm CircleCI Codacy grade Contributor Covenant

This package contains converters to and from common Unity types. Types such as Vector2, Vector3, Matrix4x4, Quaternions, Color, even ScriptableObject, and many, many more. (See the full compatibility table of all +50 supported Unity types)

Dependencies

Newtonsoft.Json packages

This package requires the Newtonsoft.Json.dll file to be present in your project. So it does not have to be used with my jillejr.newtonsoft.json-for-unity package! I recognize that there are too many Newtonsoft.Json forks and variants out there in the Unity eco-system.

This package can be combined with any of the following:

Since v3.0.1 of Unity's fork (of my fork) of Newtonsoft.Json, they are now promising a maintained version with official support by Unity's own dev team. See installation instructions here: Install official UPM package

Newtonsoft.Json versions

There's no hard linking towards a specific version. The package has been tested and works as-is with Newtonsoft.Json 10.0.3, 11.0.2, 12.0.3 and 13.0.1.

This package has not been tested towards Newtonsoft.Json versions older than v10.0.3, though the API has not changed much in a long time so it should be fine to use even as old versions as Json .NET v8.0.1 without any troubles.

If you have any troubles with using this package with a specific version of Newtonsoft.Json, then don't fray in opening an issue so we can resolve it.

Installation

OpenUPM OpenUPM icon

Add the jillejr.newtonsoft.json-for-unity.converters OpenUPM package:

openupm add jillejr.newtonsoft.json-for-unity.converters

Visit the jilleJr/Newtonsoft.Json-for-Unity/wiki to read more about installing/upgrading via OpenUPM.

Other

Visit the jilleJr/Newtonsoft.Json-for-Unity/wiki for installation:

What does it solve

A lot of Unity types causes self-referencing loops, such as the Vector3 type. While serializing the value new Vector3(0,1,0), Newtonsoft.Json will start writing:

{
  "x": 0,
  "y": 1,
  "z": 0,
  "normalized": {
    "x": 0,
    "y": 1,
    "z": 0,
    "normalized": {
      "x": 0,
      "y": 1,
      "z": 0,
      "normalized": {
        "x": 0,
        "y": 1,
        "z": 0,
        "normalized": {
          ...
        }
      }
    }
  }
}

and so on, until "recursion" error.. But there are also some types such as the UnityEngine.RandomState that has its state variables hidden.

The converters in this package takes care of these issues, as well as many more.

Sample error without this package

Given this piece of code:

using UnityEngine;
using Newtonsoft.Json;

public class NewBehaviour : MonoBehaviour {
    void Start() {
        var json = JsonConvert.SerializeObject(transform.position);
        Debug.Log("Position as JSON: " + json);
    }
}

Then the following is shown:

Error in Unity Console window

JsonSerializationException: Self referencing loop detected for property 'normalized' with type 'UnityEngine.Vector3'. Path 'normalized'.
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:347)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContainerContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.Serialization.JsonContract& memberContract, System.Object& memberValue) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:552)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:486)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:181)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:486)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContract valueContract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:181)
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs:96)
Newtonsoft.Json.JsonSerializer.SerializeInternal (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:1146)
Newtonsoft.Json.JsonSerializer.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) (at /root/repo/Src/Newtonsoft.Json/JsonSerializer.cs:1046)
Newtonsoft.Json.JsonConvert.SerializeObjectInternal (System.Object value, System.Type type, Newtonsoft.Json.JsonSerializer jsonSerializer) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:665)
Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:614)
Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value) (at /root/repo/Src/Newtonsoft.Json/JsonConvert.cs:530)
Sample.Start () (at Assets/Sample.cs:18)

Sample with this package

Same NewBehaviour script as above, but just by adding this package you instead see:

Debug message in Unity Console window

Position as JSON: {"x":201.0,"y":219.5,"z":0.0}
UnityEngine.Debug:Log(Object)
Sample:Start() (at Assets/Sample.cs:19)

Configuring converters

This package automatically adds all its converters to the JsonConvert.DefaultSettings if that value has been left untouched.

If you want to only use a certain subset of the converters, or perhaps add in some of your own custom converters, then you have some options that will be explored just below here.

Default settings

  • Use the custom Unity contract resolver that looks for [SerializeField] attributes.

  • Use only some of the Newtonsoft.Json converters, namely:

  • Use all converters from this package.

  • Use all other converters defined outside the Newtonsoft.Json namespace.

Custom settings through code

You can override these defaults mentioned above in your code whenever you're serializing/deserializing. For example:

using Newtonsoft.Json;
using Newtonsoft.Json.UnityConverters;
using Newtonsoft.Json.UnityConverters.Math;

var settings = new JsonSerializerSettings {
    Converters = new [] {
        new Vector3Converter(),
        new StringEnumConverter(),
    },
    ContractResolver = new UnityTypeContractResolver(),
};

var myObjectINeedToSerialize = new Vector3(1, 2, 3);

var json = JsonConvert.SerializeObject(myObjectINeedToSerialize, settings);

Custom settings through config file

Since v1.1.0 of this package, you can configure and override these defaults through a ScriptableObject that is saved at Assets/Resources/Newtonsoft.Json-for-Unity.Converters.asset.

To open the settings, click "Edit" in the top menu bar and select "Json.NET converters settings..."

Configuring ScriptableObject config

Within this settings page, you can enable or disable any of the converters you wish to include or omit by default.

These settings are only applied when you're using the default JsonSerializerSettings that this package has overridden. If you're setting the JsonSerializerSettings manually through code, as shown in the example above, then all of these settings will be ignored.

Contributing

Thankful that you're even reading this :)

If you want to contribute, here's what you can do:

  • Spread the word! More users → more feedback → I get more will-power to work on this project. This is the best way to contribute!

  • Open an issue. Could be a feature request for a new converter, or maybe you've found a bug?

  • Tackle one of the unassigned issues. If it looks like a fun task to solve and no one is assigned, then just comment on it and say that you would like to try it out.

  • Open a PR with some new feature or issue solved. Remember to ask before starting to work on anything, so no two are working on the same thing.

    Having a feature request or issue pop up and having the submitter suggesting themselves to later add a PR for a solution is the absolute greatest gift a repository maintainer could ever receive. 🎁

Changelog

Please see the CHANGELOG.md file inside this package.


This package is licensed under The MIT License (MIT)

Copyright (c) 2019 Kalle Fagerberg (jilleJr)
https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters

See full copyrights in LICENSE.md inside repository

More Repositories

1

kubectl-klock

A kubectl plugin to render watch output in a more readable fashion
Go
44
star
2

typ

Generic types and functions that are missing from Go, including sets, linked lists, trees, etc.
Go
32
star
3

musicforprogramming.ipfs

Unofficial port of musicforprogramming.net to be hosted on IPFS
TypeScript
11
star
4

YummyConsole

Game engine-like framework for .NET console applications
C#
6
star
5

NackademinUppgift09

Auction site, hooked up to Nackowskis API
C#
6
star
6

NackademinUppgift07

Simple pizza shop made with ASP.NET Core MVC and Entity Framework
C#
5
star
7

adventofcode-2020-fsharp

My attempt at Advent of Code 2020 using F# https://adventofcode.com/2020
F#
4
star
8

tree-sitter-risor

Risor grammar for tree-sitter
JavaScript
4
star
9

notes-old

My (old) personal wiki. Now using https://github.com/jilleJr/notes
Markdown
4
star
10

TellMe

🕹 Quiz game show game to play with your friends, made in Unity
ShaderLab
2
star
11

NackademinUppgift13-Unity

Network based multiplayer Battleship game made with Unity, using jilleJr/NackademinUppgift13-Protocol for multiplayer features.
C#
2
star
12

dinkur

Time tracking utility
Go
2
star
13

kubectl-stratagem

kubectl plugin for calling in Helldivers stratagems on your resources, FOR FREEDOM!
Go
2
star
14

RobotPlusPlus

A parser to compile a madeup RobotPlusPlus code language into G1ANT.ROBOT code.
C#
1
star
15

rng

Random number generator CLI
Go
1
star
16

flog

Filter logs on their serverity (even multiline logs), with automatic detection of log formats
Go
1
star
17

countdown

Simple countdown, basically `sleep 1s && notify-send`
Go
1
star
18

urlencode

Simple URL encoding CLI
Go
1
star
19

ggj-2023-roots

My attempt at GlobalGameJam 2023, themed: Roots
GDScript
1
star
20

namnsdag

Show which names are to be celebrated today.
Go
1
star
21

SongRater

Rate files (.mp3) via a very basic Elo algorithm
C#
1
star
22

CC-Tweaked-EmmyLua

EmmyLua annotations for CC-Tweaked
Lua
1
star
23

showksec

Decode Kubernetes secrets in CLI pipe
Go
1
star
24

adventofcode-2023-zig

My attempt at Advent of Code 2023 using Zig
Zig
1
star