c# - Serialize and Deserialize Json and Json Array in Unity -
i have list of items send php file unity using www
. www.text
looks [{"playerid":"1","playerloc":"powai"},{"playerid":"2","playerloc":"andheri"},{"playerid":"3","playerloc":"churchgate"}]
trim []
string. when try parse using boomlagoon.json
, first object retrieved. found out have deserialize()
list , have imported minijson.
but confused how deserialize() list. want loop through every json object , retrieve data. how can in unity using c#?
the class using
public class player { public string playerid { get; set; } public string playerloc { get; set; } public string playernick { get; set; } }
after trimming []
able parse json using minijson. returning first keyvaluepair
.
idictionary<string,object> s = json.deserialize(servicedata) idictionary<string,object>; foreach (keyvaluepair<string, object> kvp in s) { debug.log(string.format("key = {0}, value = {1}", kvp.key, kvp.value)); }
thanks!
unity added jsonutility api after 5.3.3 update. forget 3rd party libraries unless doing more complicated. jsonutility faster other json libraries. update unity 5.3.3 version or above try solution below.
jsonutility
lightweight api. simple types supported. not support collections such dictionary. 1 exception list
. supports list
, list
array!
if need serialize dictionary
or other serializing , deserializing simple datatypes, use third-party api. otherwise, continue reading.
example class serialize:
[serializable] public class player { public string playerid; public string playerloc; public string playernick; }
1. 1 data object (non-array json)
serializing part a:
serialize json public static string tojson(object obj);
method.
player playerinstance = new player(); playerinstance.playerid = "8484239823"; playerinstance.playerloc = "powai"; playerinstance.playernick = "random nick"; //convert jason string playertojason = jsonutility.tojson(playerinstance); debug.log(playertojason);
output:
{"playerid":"8484239823","playerloc":"powai","playernick":"random nick"}
serializing part b:
serialize json public static string tojson(object obj, bool prettyprint);
method overload. passing true
jsonutility.tojson
function format data. compare output below output above.
player playerinstance = new player(); playerinstance.playerid = "8484239823"; playerinstance.playerloc = "powai"; playerinstance.playernick = "random nick"; //convert jason string playertojason = jsonutility.tojson(playerinstance, true); debug.log(playertojason);
output:
{ "playerid": "8484239823", "playerloc": "powai", "playernick": "random nick" }
deserializing part a:
deserialize json 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 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 public static void fromjsonoverwrite(string json, object objecttooverwrite);
method. when jsonutility.fromjsonoverwrite
used, no new instance of object deserializing created. re-use instance pass in , overwrite values.
this efficient , should 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 values in 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. example playerid
appeared more once. unity's jsonutility
not support array still new can use helper class person array working jsonutility
.
create class called jsonhelper
. copy jsonhelper directly 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 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 = "{\r\n \"items\": [\r\n {\r\n \"playerid\": \"8484239823\",\r\n \"playerloc\": \"powai\",\r\n \"playernick\": \"random nick\"\r\n },\r\n {\r\n \"playerid\": \"512343283\",\r\n \"playerloc\": \"user2\",\r\n \"playernick\": \"rand nick 2\"\r\n }\r\n ]\r\n}"; player[] player = jsonhelper.fromjson<player>(jsonstring); debug.log(player[0].playerloc); debug.log(player[1].playerloc);
output:
powai
user2
if json array server , did not create hand:
you may have add {"items":
in front of received string add }
@ end of it.
i made simple function this:
string fixjson(string value) { value = "{\"items\":" + value + "}"; return value; }
then can use it:
string jsonstring = fixjson(yourjsonfromserver); player[] player = jsonhelper.fromjson<player>(jsonstring);
3.deserialize json string without class && de-serializing json numeric properties
this json starts 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
not support because "15m" property starts number. class variable cannot start integer.
download simplejson.cs
unity's wiki.
to "15m" property of usd:
var n = json.parse(yourjsonstring); string price = n["usd"]["15m"].value; debug.log(price);
to "15m" property of isk:
var n = json.parse(yourjsonstring); string price = n["isk"]["15m"].value; debug.log(price);
to "15m" property of nzd:
var n = json.parse(yourjsonstring); string price = n["nzd"]["15m"].value; debug.log(price);
the rest of json properties doesn't start numeric digit can handled unity's jsonutility.
4.troubleshooting jsonutility:
problems when serializing jsonutility.tojson
?
getting empty string or "{}
" jsonutility.tojson
?
a. make sure class not array. if is, use helper class above jsonhelper.tojson
instead of jsonutility.tojson
.
b. add [serializable]
top of class serializing.
c. remove property class. example, in variable, public string playerid { get; set; }
remove { get; set; }
. unity cannot serialize this.
problems when deserializing jsonutility.fromjson
?
a. if null
, make sure json not json array. if is, use helper class above jsonhelper.fromjson
instead of jsonutility.fromjson
.
b. if nullreferenceexception
while deserializing, add [serializable]
top of class.
c.any other problems, verify json valid. go site here , paste json. should show if json valid. should generate proper class json. make sure remove remove { get; set; }
each variable , add [serializable]
top of each class generated.
newtonsoft.json:
if reason newtonsoft.json must used check out forked version unity here. note may experience crash if feature used. careful.
to answer question:
your original data is
[{"playerid":"1","playerloc":"powai"},{"playerid":"2","playerloc":"andheri"},{"playerid":"3","playerloc":"churchgate"}]
add {"items":
in front of add }
@ end of it.
code this:
servicedata = "{\"items\":" + servicedata + "}";
now have:
{"items":[{"playerid":"1","playerloc":"powai"},{"playerid":"2","playerloc":"andheri"},{"playerid":"3","playerloc":"churchgate"}]}
to serialize multiple data php arrays, can do
public player[] playerinstance; playerinstance = jsonhelper.fromjson<player>(servicedata);
playerinstance[0]
first data
playerinstance[1]
second data
playerinstance[2]
third data
or data inside class playerinstance[0].playerloc
, playerinstance[1].playerloc
, playerinstance[2].playerloc
......
you can use playerinstance.length
check length before accessing it.
note: remove { get; set; }
player
class. if have { get; set; }
, wont work. unity's jsonutility
not work class members defined properties.
Comments
Post a Comment