Skip to main content

JSON in Luna

In order to serialize JSON in Luna you will need to include and use Newtonsoft.Json in your Unity project, as we do not support UnityEngine.JsonUtility. Whilst it is true we do not usually handle dlls as their contents are unreadable when exporting, we have implemented a JS translated version of the Newtonsoft.Json in our Luna engine.

Installing Newtonsoft.Json

Firstly, open your project directory and locate the manifest.json file under the Packages folder.

images-small

Add the following line to the dependencies section of the file and save:

    "com.unity.nuget.newtonsoft-json": "2.0.0"

images-medium

In this way, Package Manager handles the installation of Newtonsoft Json automatically.

Verify the package installation by opening the Package Manager interface in Unity and sorting the results by "In Project". You should see the Newtonsoft Json package among the results.

images-small

You cannot install Newtonsoft Json by searching it in the Package Manager interface, for this reason you need to add it manually to the manifest.json file in order to install it.

From here you are good to use Newtonsoft.Json (via including the namespace using Newtonsoft.Json; in your scripts).

Install Newtonsoft.Json manually

We highly recommend you use the installation method provided above. The following is a tutorial on how to install Newtonsoft Json manually in your project without using Package Manager.

CLICK ME

First you will need to download the Newtonsoft package from NuGet (link here).

images-medium

After downloading the package you will see the file type is .nupkg, change this to .zip and then extract the contents.

images-small

Inside the extracted contents navigate to /lib/netstandard2.0 and copy the Newtonsoft.Json.dll file.

Now inside your Unity project create a new folder in the root of Assets and call it 'Plugins' (the naming here is important as this is a special folder name within Unity). Inside this Plugins folder paste the Newtonsoft.Json.dll file.

From here you are good to use Newtonsoft.Json

(via including the namespace using Newtonsoft.Json; in your scripts).

Supported Methods

Note: When printing values relating to deserialized objects, you will need to use Console.WriteLine in order for them to show up in the browser console. You can use Debug.Log when checking them inside Unity though.

Writing To & Reading From Files

Whilst we can still read from files once the project is built, we cannot write to them as we don't have permission to store data (no drive access).

This means you can preprocess any writing being done in the project, and replace any reading logic using paths by adding a public TextAsset to the script and using it in place of paths.

E.g.

    // Before
JsonConvert.DeserializeObject<Product>(File.ReadAllText("Assets/products.json"));
// After
public TextAsset _json; // Drag JSON file from within Assets to this exposed field
JsonConvert.DeserializeObject<Product>(_json.text);

SerializeObject

Serializes the specified object to a JSON string. Available at runtime.

More info in Newtonsoft.Json's documentation.

JsonConvert.SerializeObject(Object);
JsonConvert.SerializeObject(Object, Formatting);
JsonConvert.SerializeObject(Object, JsonSerializerSettings);
JsonConvert.SerializeObject(Object, Formatting, JsonSerializerSettings);

DeserializeObject

Deserializes the JSON to a .NET object. Available at runtime.

More info in Newtonsoft.Json's documentation.

JsonConvert.DeserializeObject(String);
JsonConvert.DeserializeObject(String, Type);
JsonConvert.DeserializeObject(String, JsonSerializerSettings);
JsonConvert.DeserializeObject(String, Type, JsonSerializerSettings);

PopulateObject

Populates the specified object following the description in a JSON string. Available at runtime.

More info in Newtonsoft.Json's documentation.

JsonConvert.PopulateObject(String, Object);
JsonConvert.PopulateObject(String, Object, JsonSerializerSettings);

Unsupported Data Types / Structures / Encodings

Our implementation of Newtonsoft.Json supports all data types, structs and encodings other than a few exceptions:

  • Stacks
  • Queues
  • UTF7 encoding
  • UTF32 encoding

Note: Whilst we do support private properties, you will need to add a `[JsonProperty] attribute to them in order for them to serializable.

Example

using UnityEngine;
using System;
using System.IO;
using Newtonsoft.Json;

public class jsonTest : MonoBehaviour
{
// Attach your json file to the script
public TextAsset jsonFile;

private void Start()
{
JsonFunc(jsonFile);
}

public static void JsonFunc(TextAsset _json)
{
// Path will not be used in build
string path = "Assets/jsonData.json";

// Initialise data
Product product = new Product();

product.Name = "Apple";
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

// Write to file only outside of Luna
#if !UNITY_LUNA
File.WriteAllText(path, JsonConvert.SerializeObject(product));
#endif

// Deserialize the JSON and assign to variable
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(_json.text);

// Log the properties
// (Remember you need Console.WriteLine to see them in the browser console)
Console.WriteLine(deserializedProduct.Name);
Console.WriteLine(deserializedProduct.Price);

for (int i = 0; i < product.Sizes.Length; i++){
Console.WriteLine(deserializedProduct.Sizes[i]);
}
}
}

public class Product
{
public string Name { get; set; }

public decimal Price { get; set; }

public string[] Sizes { get; set; }
}