144

I have a list of items send from a PHP file to unity using WWW.

The WWW.text looks like:

[
    {
        "playerId": "1",
        "playerLoc": "Powai"
    },
    {
        "playerId": "2",
        "playerLoc": "Andheri"
    },
    {
        "playerId": "3",
        "playerLoc": "Churchgate"
    }
]

Where I trim the extra [] from the string. When I try to parse it using Boomlagoon.JSON, only the first object is retrieved. I found out that I have to deserialize() the list and have imported MiniJSON.

But I am confused how to deserialize() this list. I want to loop through every JSON object and retrieve data. How can I do this in Unity using C#?

The class I am using is

public class player
{
    public string playerId { get; set; }
    public string playerLoc { get; set; }
    public string playerNick { get; set; }
}

After trimming the [] I am able to parse the json using MiniJSON. But it is returning only the first KeyValuePair.

IDictionary<string, object> players = Json.Deserialize(serviceData) as IDictionary<string, object>;

foreach (KeyValuePair<string, object> kvp in players)
{
    Debug.Log(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}

Thanks!

Snak
  • 673
  • 1
  • 5
  • 19
dil33pm
  • 1,613
  • 2
  • 13
  • 18
  • Why did you remove the outer `[` and `]`? That's what makes it a list. Just stop removing that, and deserialize it as an array or a list and I'd expect it to be fine. Please post the code that you've tried. – Jon Skeet Mar 26 '16 at 19:17
  • Show us the class used for deserialization. The format is weird, why is the second playerId not wrapped inside curly braces? It should deserialize to a list of something, like `List`, because this **is** an array. – Maximilian Gerhardt Mar 26 '16 at 19:17
  • @MaximilianGerhardt Sorry the curly braces was a typo. Fixed it in the question and added the code also. Thanks. – dil33pm Mar 26 '16 at 20:36
  • 1
    I think there's something wrong with your understanding of thow *this* library here handles deserializiation. It isn't the usual deserialization (as you've maybe seein in `Newtonsoft.Json`), but the `Json.Deserialize()` ALWAYS returnes a `IDictionary` to you and you operate on `List`. Look at http://stackoverflow.com/a/22745634/5296568 . Preferably, get a better JSON deserializer which does the deserialization you're used to. – Maximilian Gerhardt Mar 26 '16 at 20:56
  • @MaximilianGerhardt I tried with `IDictionary`. I am able to get the value out, but only the first `KeyValuePair<>`. – dil33pm Mar 27 '16 at 04:30

10 Answers10

353

Unity added JsonUtility to their API after 5.3.3 Update. Forget about all the 3rd party libraries unless you are doing something more complicated. JsonUtility is faster than other Json libraries. Update to Unity 5.3.3 version or above then try the solution below.

JsonUtility is a lightweight API. Only simple types are supported. It does not support collections such as Dictionary. One exception is List. It supports List and List array!

If you need to serialize a Dictionary or do something other than simply serializing and deserializing simple datatypes, use a third-party API. Otherwise, continue reading.

Example class to serialize:

[Serializable]
public class Player
{
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

1. ONE DATA OBJECT (NON-ARRAY JSON)

Serializing Part A:

Serialize to Json with the public static string ToJson(object obj); method.

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJson);

Output:

{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}

Serializing Part B:

Serialize to Json with the public static string ToJson(object obj, bool prettyPrint); method overload. Simply passing true to the JsonUtility.ToJson function will format the data. Compare the output below to the output above.

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJson);

Output:

{
    "playerId": "8484239823",
    "playerLoc": "Powai",
    "playerNick": "Random Nick"
}

Deserializing Part A:

Deserialize json with the public static T FromJson(string json); method overload.

string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);

Deserializing Part B:

Deserialize json with the public static object FromJson(string json, Type type); method overload.

string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);

Deserializing Part C:

Deserialize json with the public static void FromJsonOverwrite(string json, object objectToOverwrite); method. When JsonUtility.FromJsonOverwrite is used, no new instance of that Object you are deserializing to will be created. It will simply re-use the instance you pass in and overwrite its values.

This is efficient and should be used if possible.

Player playerInstance;
void Start()
{
    //Must create instance once
    playerInstance = new Player();
    deserialize();
}

void deserialize()
{
    string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";

    //Overwrite the values in the existing class instance "playerInstance". Less memory Allocation
    JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
    Debug.Log(playerInstance.playerLoc);
}

2. MULTIPLE DATA(ARRAY JSON)

Your Json contains multiple data objects. For example playerId appeared more than once. Unity's JsonUtility does not support array as it is still new but you can use a helper class from this person to get array working with JsonUtility.

Create a class called JsonHelper. Copy the JsonHelper directly from below.

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

Serializing Json Array:

Player[] playerInstance = new Player[2];

playerInstance[0] = new Player();
playerInstance[0].playerId = "8484239823";
playerInstance[0].playerLoc = "Powai";
playerInstance[0].playerNick = "Random Nick";

playerInstance[1] = new Player();
playerInstance[1].playerId = "512343283";
playerInstance[1].playerLoc = "User2";
playerInstance[1].playerNick = "Rand Nick 2";

//Convert to JSON
string playerToJson = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJson);

Output:

{
    "Items": [
        {
            "playerId": "8484239823",
            "playerLoc": "Powai",
            "playerNick": "Random Nick"
        },
        {
            "playerId": "512343283",
            "playerLoc": "User2",
            "playerNick": "Rand Nick 2"
        }
    ]
}

Deserializing Json Array:

string jsonString = "{\r\n    \"Items\": [\r\n        {\r\n            \"playerId\": \"8484239823\",\r\n            \"playerLoc\": \"Powai\",\r\n            \"playerNick\": \"Random Nick\"\r\n        },\r\n        {\r\n            \"playerId\": \"512343283\",\r\n            \"playerLoc\": \"User2\",\r\n            \"playerNick\": \"Rand Nick 2\"\r\n        }\r\n    ]\r\n}";

Player[] player = JsonHelper.FromJson<Player>(jsonString);
Debug.Log(player[0].playerLoc);
Debug.Log(player[1].playerLoc);

Output:

Powai

User2


If this is a Json array from the server and you did not create it by hand:

You may have to Add {"Items": in front of the received string then add } at the end of it.

I made a simple function for this:

string fixJson(string value)
{
    value = "{\"Items\":" + value + "}";
    return value;
}

then you can use it:

string jsonString = fixJson(yourJsonFromServer);
Player[] player = JsonHelper.FromJson<Player>(jsonString);

3.Deserialize json string without class && De-serializing Json with numeric properties

This is a Json that starts with a number or numeric properties.

For example:

{ 
"USD" : {"15m" : 1740.01, "last" : 1740.01, "buy" : 1740.01, "sell" : 1744.74, "symbol" : "$"}, 

"ISK" : {"15m" : 179479.11, "last" : 179479.11, "buy" : 179479.11, "sell" : 179967, "symbol" : "kr"},

"NZD" : {"15m" : 2522.84, "last" : 2522.84, "buy" : 2522.84, "sell" : 2529.69, "symbol" : "$"}
}

Unity's JsonUtility does not support this because the "15m" property starts with a number. A class variable cannot start with an integer.

Download SimpleJSON.cs from Unity's wiki.

To get the "15m" property of USD:

var N = JSON.Parse(yourJsonString);
string price = N["USD"]["15m"].Value;
Debug.Log(price);

To get the "15m" property of ISK:

var N = JSON.Parse(yourJsonString);
string price = N["ISK"]["15m"].Value;
Debug.Log(price);

To get the "15m" property of NZD:

var N = JSON.Parse(yourJsonString);
string price = N["NZD"]["15m"].Value;
Debug.Log(price);

The rest of the Json properties that doesn't start with a numeric digit can be handled by Unity's JsonUtility.


4.TROUBLESHOOTING JsonUtility:

Problems when serializing with JsonUtility.ToJson?

Getting empty string or "{}" with JsonUtility.ToJson?

A. Make sure that the class is not an array. If it is, use the helper class above with JsonHelper.ToJson instead of JsonUtility.ToJson.

B. Add [Serializable] to the top of the class you are serializing.

C. Remove property from the class. For example, in the variable, public string playerId { get; set; } remove { get; set; }. Unity cannot serialize this.

Problems when deserializing with JsonUtility.FromJson?

A. If you get Null, make sure that the Json is not a Json array. If it is, use the helper class above with JsonHelper.FromJson instead of JsonUtility.FromJson.

B. If you get NullReferenceException while deserializing, add [Serializable] to the top of the class.

C.Any other problems, verify that your json is valid. Go to this site here and paste the json. It should show you if the json is valid. It should also generate the proper class with the Json. Just make sure to remove remove { get; set; } from each variable and also add [Serializable] to the top of each class generated.


Newtonsoft.Json:

If for some reason Newtonsoft.Json must be used then as of February 2022 it may now be obtained directly from Unity from here: com.unity.nuget.newtonsoft-json@3.0. Just add com.unity.nuget.newtonsoft-json via the package manager. For details see Install official via UPM by kalle (jag).

You can also check out the forked version for Unity from SaladLab / Json.Net.Unity3D. Note that you may experience crash if certain feature is used. Be careful.


To answer your question:

Your original data is

 [{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]

Add {"Items": in front of it then add } at the end of it.

Code to do this:

serviceData = "{\"Items\":" + serviceData + "}";

Now you have:

 {"Items":[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]}

To serialize the multiple data from php as arrays, you can now do

public player[] playerInstance;
playerInstance = JsonHelper.FromJson<player>(serviceData);

playerInstance[0] is your first data

playerInstance[1] is your second data

playerInstance[2] is your third data

or data inside the class with playerInstance[0].playerLoc, playerInstance[1].playerLoc, playerInstance[2].playerLoc ......

You can use playerInstance.Length to check the length before accessing it.

NOTE: Remove { get; set; } from the player class. If you have { get; set; }, it won't work. Unity's JsonUtility does NOT work with class members that are defined as properties.

dbc
  • 104,963
  • 20
  • 228
  • 340
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • I am returning an array of rows of a `mysql` query from PHP using `json_encode($row)`. So the response consists of multiple JSONObjects in the format `[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]`. I tried JsonUtility, but I couldn't deserialize the objects and get individual json objects. If you can help me with that. – dil33pm Mar 27 '16 at 06:58
  • 2
    Look at the code I posted above. It shows you three ways to do that with `JsonUtility.FromJson`. I forgot to tell you to remove `{ get; set; }` from the `player` class. If you have `{ get; set; }`, it wont work. Compare your `player` class with the one I posted above and you will understand what I am saying. – Programmer Mar 27 '16 at 07:04
  • 1
    No problem. I will edit this when Unity adds support for array(which is very soon) so you won't need that Helper class anymore. – Programmer Mar 27 '16 at 17:16
  • It's been months and "very soon" hasn't come yet. Every web technology out there uses JSON and we still don't have this... – Vlady Veselinov Nov 29 '16 at 17:47
  • 3
    I would not go as far as to say "Forget about all the 3rd party libraries". JsonUtility has limitations. It does not return a JSON object on which you can perform actions. For instance, I get a json file and want to check whether a "success" key is available. Can't do. The JsonUtility requires the consumer knows the exact content of the json file. Also, no Dictionary converter. So it does some good things but the usage of 3rd party is still required. – Everts Feb 03 '17 at 08:28
  • @Everts I know. It's a lightweight serializer. It works for 90 percent of questions asked about json on this site. For this question, it should do the job too. I modified the question to add that at the top. – Programmer Feb 03 '17 at 18:07
  • Hey @Programmer , first off, great post, I've been searching/coding for a Json array readin method for about 3 hours now. I'm new to Unity and, coming from a web background, it seems so natural to store game data into JSON format.. a bit disappointed that Unity does not have a better JSON reading/writing system out-of-the-box. So, out of the 2 options: Break pattern and make a separate JSON file for every weapon in the game + one json file to hold all references OR hack json reading it off with some extra code (JsonHelper) to read arrays, which would you say is better? – sigmaxf Mar 08 '17 at 16:12
  • 3
    Use `JsonHelper`. It's fine. If you create Json with it, you can also read json with it without extra steps. The only time you may need to do extra stuff is if you are receiving the json array from the server and that is included in the solution is in my answer. Another way without `JsonHelper` is to put the class in another class then make it a `List`. This has been working for most people. If you are looking for a way to save and load game data then see [this](http://stackoverflow.com/a/40966346/3785314). *You load and save with one line of code.* – Programmer Mar 08 '17 at 16:42
  • "Another way without JsonHelper is to put the class in another class then make it a List. This has been working for most people." - How would that work? This might be just what I'm looking for. – sigmaxf Mar 09 '17 at 00:24
  • On the contrary, I recommend using a third-party flexible library: custom serialization / deserialization, property serialization, mapping object fields to Json fields, ignoring fields, using constructors, etc. Simply put, it does not support the JSON standard convention (ex. top level arrays). Yes, [JsonUtility](https://docs.unity3d.com/ScriptReference/JsonUtility.html) the fastest, but Json-serialization usually occurs during asynchronous operations or serves to save some data, and at such times several tens of milliseconds do not play a big role. – Ruslan L. May 13 '17 at 09:17
  • My webserver returns array of array of object, each object are like `{"c":"xx", "d":"yy"}`. You gave a lot of examples, but not array of array... may I ask you to give one? I'd like to find out how to make a working loop with this `SimpleJSON.JSONNode a = SimpleJSON.JSON.Parse("[[{\"c\": 1, \"d\": 1},{\"c\": 1, \"d\": 1}]]");` My loops begin like this and are ok but i cant access the properties c and d of each object: `foreach (SimpleJSON.JSONNode row in a) { foreach (SimpleJSON.JSONNode cell in row) { var j = cell.AsObject; Debug.Log(j['c']); } }` – Olivier Pons Dec 21 '17 at 23:42
  • You only use SimpleJSON if Unity's JsonUtility cannot serialize that. What exactly are you receiving from the server? Just post it as it is and I will help you out – Programmer Dec 21 '17 at 23:54
  • Just in case you want to serialize with the same JSON format `[{...},{...}]` but you're getting `{"objectName": [{...},{...}] }}`. Remember that you can "cut" the string with 2 simple lines of code in C# like: `String result = JsonUtility.ToJson(list); result = result.Substring(result.IndexOf("[")); //Remove everything before [ result = result.Substring(0, result.LastIndexOf("]") + 1); //Remove everything after ]` – Lotan Mar 31 '18 at 14:17
  • The `JsonHelper` didn't work for me. Probably because I was trying to serialize an array of struct, not class. I modified it to serialize each element individually, and the join them while enclosing them inside square brackets. – Akhil Gupta Feb 06 '19 at 10:27
  • 1
    Note that in newer version Newtonsoft JSON comes semi "built-in" as a [Package](https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@2.0/manual/index.html) via the Package Manager! It is way more powerful and e.g. supports: Properties, Dictionaries, nested arrays etc – derHugo May 16 '21 at 18:31
  • I'm sorry, but JsonUtility is not robust enough for complex scenarios. – jhchnc Jun 06 '21 at 14:24
  • SimpleJSON is no longer on Unity's pages (as they are recommending JsonUtility). However it is still available via Git: https://github.com/Bunny83/SimpleJSON NB: See the Github Wiki for usage details as the README is empty. – Paul Masri-Stone Oct 29 '21 at 16:56
  • This troubleshooting section doesn't even begin to cover all the issues a user will face when working with parent/child classes with JSONUtility. JSONUtility is buggy and shouldn't be used. I found out the hard way after hours of debugging. Someone with a similar problem in https://answers.unity.com/questions/1400802/json-serialization-of-derived-classes.html – pete Feb 01 '22 at 21:10
24

Assume you got a JSON like this

[
    {
        "type": "qrcode",
        "symbol": [
            {
                "seq": 0,
                "data": "HelloWorld9887725216",
                "error": null
            }
        ]
    }
]

To parse the above JSON in unity, you can create JSON model like this.

[System.Serializable]
public class QrCodeResult
{
    public QRCodeData[] result;
}

[System.Serializable]
public class Symbol
{
    public int seq;
    public string data;
    public string error;
}

[System.Serializable]
public class QRCodeData
{
    public string type;
    public Symbol[] symbol;
}

And then simply parse in the following manner...

var myObject = JsonUtility.FromJson<QrCodeResult>("{\"result\":" + jsonString.ToString() + "}");

Now you can modify the JSON/CODE according to your need. https://docs.unity3d.com/Manual/JSONSerialization.html

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Narottam Goyal
  • 3,534
  • 27
  • 26
  • This actually works quite well, got it working with a class like Symbol that is not an array as well. – Gennon May 14 '18 at 14:46
  • 4
    I'm trying this with unity 2018 but this does not work: the arrays aren't parsed – Jean-Michaël Celerier Oct 06 '18 at 13:04
  • Used in unity 2018 and 2019. Works great. Access the array data like: `Debug.Log(myObject.result[0].symbol[0].data);` or `for(var i = 0; i <= myObject.result.Length - 1; i ++) { Debug.Log(myObject.result[i].type); }` or `foreach (var item in myObject.result) { Debug.Log(item.type); }` – Towerss Apr 29 '19 at 05:26
  • @Narottam Goyal, your method is not working in some cases, also a very difficult solution for beginners, refer this answer by me on this thread [link](https://stackoverflow.com/a/56146280/8304176) – Junaid Pathan May 15 '19 at 09:47
  • @JunedKhanMomin your answer does basically the same but without adressing the fact that this question here was about a **root level array** in the JSON data in specific. In general you should rather refer to [Programmer's answer](https://stackoverflow.com/a/36244111/7111561) which is way more elaborated. – derHugo Jun 07 '19 at 03:57
5

Unity <= 2019

Narottam Goyal had a good idea of wrapping the array in a json object, and then deserializing into a struct. The following uses Generics to solve this for arrays of all type, as opposed to making a new class everytime.

[System.Serializable]
private struct JsonArrayWrapper<T> {
    public T wrap_result;
}

public static T ParseJsonArray<T>(string json) {
    var temp = JsonUtility.FromJson<JsonArrayWrapper<T>>("{\"wrap_result\":" + json + "}");
    return temp.wrap_result;
}

It can be used in the following way:

string[] options = ParseJsonArray<string[]>(someArrayOfStringsJson);

Unity 2020

In Unity 2020 there is an official newtonsoft package which is a far better json library.

Justin Meiners
  • 10,754
  • 6
  • 50
  • 92
  • 5
    The link you provided is dead, but this link is listed as related article: https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@2.0/manual/index.html with note: "This is a package intended for internal Unity Development Projects and as such this package is not supported. Use at your own risk." – R2RT Sep 17 '20 at 16:31
  • Does that first solution still work? All I get is a null value for wrap_result. – david.pfx Apr 06 '21 at 09:01
  • @david.pfx there is a typo that has been fixed, how about now? – Justin Meiners Apr 09 '21 at 00:57
  • Sorry, can't test it, switched to Newtonsoft to keep things moving. But I'll give it another try when I have time -- I really don't want to add an unnecessary dependency. – david.pfx Apr 10 '21 at 04:17
  • 2
    Finally got serialization that supports polymorphism in Unity now thanks to this package. In Unity, just open the Package Manager windows, and then choose to add a package by name, and provide `com.unity.nuget.newtonsoft-json` as the name. – Peppe L-G Sep 02 '21 at 13:50
3

you have to add [System.Serializable] to PlayerItem class ,like this:

using System;
[System.Serializable]
public class PlayerItem   {
    public string playerId;
    public string playerLoc;
    public string playerNick;
}
Garf365
  • 3,619
  • 5
  • 29
  • 41
Myan
  • 39
  • 1
0

Like @Maximiliangerhardt said, MiniJson do not have the capability to deserialize properly. I used JsonFx and works like a charm. Works with the []

player[] p = JsonReader.Deserialize<player[]>(serviceData);
Debug.Log(p[0].playerId +" "+ p[0].playerLoc+"--"+ p[1].playerId + " " + p[1].playerLoc+"--"+ p[2].playerId + " " + p[2].playerLoc);
dil33pm
  • 1,613
  • 2
  • 13
  • 18
0

To Read JSON File, refer this simple example

Your JSON File (StreamingAssets/Player.json)

{
    "Name": "MyName",
    "Level": 4
}

C# Script

public class Demo
{
    public void ReadJSON()
    {
        string path = Application.streamingAssetsPath + "/Player.json";
        string JSONString = File.ReadAllText(path);
        Player player = JsonUtility.FromJson<Player>(JSONString);
        Debug.Log(player.Name);
    }
}

[System.Serializable]
public class Player
{
    public string Name;
    public int Level;
}
Junaid Pathan
  • 3,850
  • 1
  • 25
  • 47
  • 2
    What about arrays? And what does this answer add that wasn't metnioned already in [the accepted answer](https://stackoverflow.com/a/36244111/7111561) from over 3 years ago? – derHugo Jul 01 '19 at 06:23
  • @derHugo it includes a call to `File.ReadAllText` which I think is helpful and no other answer mentions :) – Ruzihm Sep 23 '20 at 22:09
  • 1
    @Ruzihm well the reason why no other answer mentioned it is because this question's scope is how to (de)serialize .. not how to do FileIO ;) – derHugo Sep 24 '20 at 06:59
0

You can use Newtonsoft.Json just add Newtonsoft.dll to your project and use below script

using System;
using Newtonsoft.Json;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    [Serializable]
    public class Person
    {
        public string id;
        public string name;
    }
    public Person[] person;

    private void Start()
    {
       var myjson = JsonConvert.SerializeObject(person);

        print(myjson);

    }
}

enter image description here

another solution is using JsonHelper

using System;
using Newtonsoft.Json;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    [Serializable]
    public class Person
    {
        public string id;
        public string name;
    }
    public Person[] person;

    private void Start()
    {
        var myjson = JsonHelper.ToJson(person);

        print(myjson);

    }
}

enter image description here

Seyed Morteza Kamali
  • 806
  • 1
  • 10
  • 22
  • 2
    Note that newtonsoft does not seem to be working in unity when you build on android for example. It will work on the unity editor though.. Seems a fork of newtonsoft for unity is recommended in that case https://stackoverflow.com/questions/59194154/newtonsoft-json-works-in-unity-editor-but-not-on-mobile-devices – Rose Nov 22 '20 at 06:25
0

If you came here looking for how to serialize a List using JsonUtility without any extra packages, read on.

[System.Serializable]
public class JsonableListWrapper<T>
{
    public List<T> list;
    public JsonableListWrapper(List<T> list) => this.list = list;
}

Example usage:

List<string> stringList = new List<string>(){"one","two","three"};
// To Json
string stringListAsJson = JsonUtility.ToJson(new JsonListWrapper<string>(stringList));
// From Json
List<string> stringListFromJson = JsonUtility.FromJson<JsonListWrapper<string>>(stringListAsJson).list;

Credit to theonlysake from this thread: https://forum.unity.com/threads/jsonutilities-tojson-with-list-string-not-working-as-expected.722783/

It seems you can't serialize/deserialize a List directly, but if it's a property of a class you can. In my own personal case, I replaced the string type with the type of a custom class and it worked great.

seth
  • 63
  • 1
  • 2
  • 8
-1

Don't trim the [] and you should be fine. [] identify a JSON array which is exactly what you require to be able to iterate its elements.

Thomas Hilbert
  • 3,559
  • 2
  • 13
  • 33
-1

IF you are using Vector3 this is what i did

1- I create a class Name it Player

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
    public Vector3[] Position;

}

2- then i call it like this

if ( _ispressed == true)
        {
            Player playerInstance = new Player();
            playerInstance.Position = newPos;
            string jsonData = JsonUtility.ToJson(playerInstance);

            reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
            Debug.Log(jsonData);
            _ispressed = false;
        }

3- and this is the result

"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}

Gara
  • 143
  • 1
  • 4
  • 12