How to convert an object into Json String in Unity3D Script (C#)

|
| By Webner

How to convert an object into JSON String in Unity3D Script (C#)?

Let’s say I have a class:

class User {
String firstName;
String lastName;
String userName;
}
User obj = new User
{
firstName = "Shalini",
lastName = "Vashist",
userName = “shalini.vashist”
};
And In
return I need a JSON string like this
for user object:
{“
firstName”: “Shalini”,
“lastName”: “Vashist”,
“userName”: “shalini.vashist”
}

For this we can use Simple method( ToJson) of JSON utility class:

string jsonResult = JSON utility.ToJson(obj);

For more details you can refer to JSON serialization section under Unity’s Official Documentation:

https://docs.unity3d.com/Manual/JSONSerialization.html

Sometimes developers get confused with Unity app opened in Visual Studio with Web applications created in Visual Studio.

And they try to use the following method to convert the object into JSON String:

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

It will throw the following error:

The type or namespace name “Web” does not exist in the namespace “System.” (are you missing an assembly reference?)

 

Leave a Reply

Your email address will not be published. Required fields are marked *