Serialize and Deserialize Json and Json Array in Unity











up vote
57
down vote

favorite
39












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> s = Json.Deserialize(serviceData) as IDictionary<string,object>;
foreach (KeyValuePair<string, object> kvp in s)
{
Debug.Log(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}


Thanks!










share|improve this question
























  • 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<PlayerLocation>, 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<string,object> to you and you operate on List<object>. Look at 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<string,object>. I am able to get the value out, but only the first KeyValuePair<>.
    – dil33pm
    Mar 27 '16 at 4:30















up vote
57
down vote

favorite
39












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> s = Json.Deserialize(serviceData) as IDictionary<string,object>;
foreach (KeyValuePair<string, object> kvp in s)
{
Debug.Log(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}


Thanks!










share|improve this question
























  • 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<PlayerLocation>, 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<string,object> to you and you operate on List<object>. Look at 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<string,object>. I am able to get the value out, but only the first KeyValuePair<>.
    – dil33pm
    Mar 27 '16 at 4:30













up vote
57
down vote

favorite
39









up vote
57
down vote

favorite
39






39





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> s = Json.Deserialize(serviceData) as IDictionary<string,object>;
foreach (KeyValuePair<string, object> kvp in s)
{
Debug.Log(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}


Thanks!










share|improve this question















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> s = Json.Deserialize(serviceData) as IDictionary<string,object>;
foreach (KeyValuePair<string, object> kvp in s)
{
Debug.Log(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}


Thanks!







c# json unity3d






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 15 '17 at 7:39









Luzan Baral

2,08312055




2,08312055










asked Mar 26 '16 at 19:13









dil33pm

3731416




3731416












  • 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<PlayerLocation>, 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<string,object> to you and you operate on List<object>. Look at 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<string,object>. I am able to get the value out, but only the first KeyValuePair<>.
    – dil33pm
    Mar 27 '16 at 4:30


















  • 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<PlayerLocation>, 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<string,object> to you and you operate on List<object>. Look at 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<string,object>. I am able to get the value out, but only the first KeyValuePair<>.
    – dil33pm
    Mar 27 '16 at 4:30
















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




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<PlayerLocation>, because this is an array.
– Maximilian Gerhardt
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<PlayerLocation>, 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




@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




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<string,object> to you and you operate on List<object>. Look at 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




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<string,object> to you and you operate on List<object>. Look at 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<string,object>. I am able to get the value out, but only the first KeyValuePair<>.
– dil33pm
Mar 27 '16 at 4:30




@MaximilianGerhardt I tried with IDictionary<string,object>. I am able to get the value out, but only the first KeyValuePair<>.
– dil33pm
Mar 27 '16 at 4:30












5 Answers
5






active

oldest

votes

















up vote
148
down vote



accepted










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 Jason
string playerToJason = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJason);


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 Jason
string playerToJason = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJason);


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 Jason
string playerToJason = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJason);


Output:



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




Deserializing Json Array:



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

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 check out the forked version for Unity here. 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 wont work. Unity's JsonUtility does NOT work with class members that are defined as properties.






share|improve this answer























  • 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 6:58






  • 1




    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 7:04












  • 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








  • 2




    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. You load and save with one line of code.
    – Programmer
    Mar 8 '17 at 16:42






  • 1




    See here
    – Programmer
    Mar 9 '17 at 0:40


















up vote
7
down vote













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






share|improve this answer























  • This actually works quite well, got it working with a class like Symbol that is not an array as well.
    – Gennon
    May 14 at 14:46






  • 1




    I'm trying this with unity 2018 but this does not work: the arrays aren't parsed
    – Jean-Michaël Celerier
    Oct 6 at 13:04


















up vote
0
down vote













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.






share|improve this answer





















  • I tried with the brackets. Still the same error.
    – dil33pm
    Mar 27 '16 at 4:00


















up vote
0
down vote













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);





share|improve this answer




























    up vote
    0
    down vote













    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;
    }





    share|improve this answer






















      protected by Programmer Feb 3 '17 at 15:12



      Thank you for your interest in this question.
      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



      Would you like to answer one of these unanswered questions instead?














      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      148
      down vote



      accepted










      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonHelper.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      Output:



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




      Deserializing Json Array:



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

      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 check out the forked version for Unity here. 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 wont work. Unity's JsonUtility does NOT work with class members that are defined as properties.






      share|improve this answer























      • 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 6:58






      • 1




        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 7:04












      • 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








      • 2




        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. You load and save with one line of code.
        – Programmer
        Mar 8 '17 at 16:42






      • 1




        See here
        – Programmer
        Mar 9 '17 at 0:40















      up vote
      148
      down vote



      accepted










      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonHelper.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      Output:



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




      Deserializing Json Array:



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

      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 check out the forked version for Unity here. 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 wont work. Unity's JsonUtility does NOT work with class members that are defined as properties.






      share|improve this answer























      • 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 6:58






      • 1




        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 7:04












      • 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








      • 2




        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. You load and save with one line of code.
        – Programmer
        Mar 8 '17 at 16:42






      • 1




        See here
        – Programmer
        Mar 9 '17 at 0:40













      up vote
      148
      down vote



      accepted







      up vote
      148
      down vote



      accepted






      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonHelper.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      Output:



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




      Deserializing Json Array:



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

      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 check out the forked version for Unity here. 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 wont work. Unity's JsonUtility does NOT work with class members that are defined as properties.






      share|improve this answer














      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonUtility.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      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 Jason
      string playerToJason = JsonHelper.ToJson(playerInstance, true);
      Debug.Log(playerToJason);


      Output:



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




      Deserializing Json Array:



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

      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 check out the forked version for Unity here. 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 wont work. Unity's JsonUtility does NOT work with class members that are defined as properties.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 23 '17 at 10:31

























      answered Mar 27 '16 at 5:19









      Programmer

      74.9k1080141




      74.9k1080141












      • 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 6:58






      • 1




        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 7:04












      • 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








      • 2




        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. You load and save with one line of code.
        – Programmer
        Mar 8 '17 at 16:42






      • 1




        See here
        – Programmer
        Mar 9 '17 at 0:40


















      • 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 6:58






      • 1




        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 7:04












      • 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








      • 2




        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. You load and save with one line of code.
        – Programmer
        Mar 8 '17 at 16:42






      • 1




        See here
        – Programmer
        Mar 9 '17 at 0:40
















      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 6:58




      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 6:58




      1




      1




      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 7:04






      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 7:04














      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






      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






      2




      2




      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. You load and save with one line of code.
      – Programmer
      Mar 8 '17 at 16:42




      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. You load and save with one line of code.
      – Programmer
      Mar 8 '17 at 16:42




      1




      1




      See here
      – Programmer
      Mar 9 '17 at 0:40




      See here
      – Programmer
      Mar 9 '17 at 0:40












      up vote
      7
      down vote













      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






      share|improve this answer























      • This actually works quite well, got it working with a class like Symbol that is not an array as well.
        – Gennon
        May 14 at 14:46






      • 1




        I'm trying this with unity 2018 but this does not work: the arrays aren't parsed
        – Jean-Michaël Celerier
        Oct 6 at 13:04















      up vote
      7
      down vote













      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






      share|improve this answer























      • This actually works quite well, got it working with a class like Symbol that is not an array as well.
        – Gennon
        May 14 at 14:46






      • 1




        I'm trying this with unity 2018 but this does not work: the arrays aren't parsed
        – Jean-Michaël Celerier
        Oct 6 at 13:04













      up vote
      7
      down vote










      up vote
      7
      down vote









      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






      share|improve this answer














      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







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 6 at 9:43









      H. Pauwelyn

      5,651174583




      5,651174583










      answered Sep 25 '17 at 20:48









      Narottam Goyal

      1,5281616




      1,5281616












      • This actually works quite well, got it working with a class like Symbol that is not an array as well.
        – Gennon
        May 14 at 14:46






      • 1




        I'm trying this with unity 2018 but this does not work: the arrays aren't parsed
        – Jean-Michaël Celerier
        Oct 6 at 13:04


















      • This actually works quite well, got it working with a class like Symbol that is not an array as well.
        – Gennon
        May 14 at 14:46






      • 1




        I'm trying this with unity 2018 but this does not work: the arrays aren't parsed
        – Jean-Michaël Celerier
        Oct 6 at 13:04
















      This actually works quite well, got it working with a class like Symbol that is not an array as well.
      – Gennon
      May 14 at 14:46




      This actually works quite well, got it working with a class like Symbol that is not an array as well.
      – Gennon
      May 14 at 14:46




      1




      1




      I'm trying this with unity 2018 but this does not work: the arrays aren't parsed
      – Jean-Michaël Celerier
      Oct 6 at 13:04




      I'm trying this with unity 2018 but this does not work: the arrays aren't parsed
      – Jean-Michaël Celerier
      Oct 6 at 13:04










      up vote
      0
      down vote













      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.






      share|improve this answer





















      • I tried with the brackets. Still the same error.
        – dil33pm
        Mar 27 '16 at 4:00















      up vote
      0
      down vote













      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.






      share|improve this answer





















      • I tried with the brackets. Still the same error.
        – dil33pm
        Mar 27 '16 at 4:00













      up vote
      0
      down vote










      up vote
      0
      down vote









      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.






      share|improve this answer












      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.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 26 '16 at 22:32









      Thomas Hilbert

      2,7532627




      2,7532627












      • I tried with the brackets. Still the same error.
        – dil33pm
        Mar 27 '16 at 4:00


















      • I tried with the brackets. Still the same error.
        – dil33pm
        Mar 27 '16 at 4:00
















      I tried with the brackets. Still the same error.
      – dil33pm
      Mar 27 '16 at 4:00




      I tried with the brackets. Still the same error.
      – dil33pm
      Mar 27 '16 at 4:00










      up vote
      0
      down vote













      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);





      share|improve this answer

























        up vote
        0
        down vote













        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);





        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          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);





          share|improve this answer












          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);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 27 '16 at 5:16









          dil33pm

          3731416




          3731416






















              up vote
              0
              down vote













              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;
              }





              share|improve this answer



























                up vote
                0
                down vote













                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;
                }





                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  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;
                  }





                  share|improve this answer














                  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;
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 5 '16 at 7:53









                  Garf365

                  3,23652135




                  3,23652135










                  answered Dec 5 '16 at 7:34









                  Myan

                  91




                  91

















                      protected by Programmer Feb 3 '17 at 15:12



                      Thank you for your interest in this question.
                      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                      Would you like to answer one of these unanswered questions instead?



                      Popular posts from this blog

                      What visual should I use to simply compare current year value vs last year in Power BI desktop

                      How to ignore python UserWarning in pytest?

                      Alexandru Averescu