0

I recently got into C# using Unity. I previously worked with JavaScript and know that they defiantly have their differences, but still have some similarities. I have used JSON with JS and it works great. Now with Unity, I want to store data of upcoming "stages" in JSON in an infinite runner game. But from my experience, JSON does not work nearly as well with C# as it does with JS. I have looked at Unity's JSON Utility but haven't figured out if it's possible to simply have a string and then convert it into an object which you could access like object.item.array[0].item which is how you'd do it in JS. Another thing that I looked at was this but as a novice to C#, I couldn't make heads or tails of it. So does C# have something like JSON, but its more integrated? I've used C# lists, can you get 3D lists with items and not just arrays? I know that they are very different languages, and what works well on one, might not on another.

Jack
  • 1,893
  • 1
  • 11
  • 28
  • The standard for json in C# is (in my opinion so not adding as an answer) Newtonsoft.Json just install the nuget package. Beyond that you'd be better off asking a specific question about a specific problem. Generic "how do lists work in C#" type questions are a bit vague to get good answers. – Ben Jun 06 '19 at 21:54
  • I'm not exactly sure what you are asking. C# is much more strongly typed than JavaScript, so "traditional" JSON techniques won't work very well. Of course you can get C# objects to and from JSON with either library mentioned. What did you want to know? – BradleyDotNET Jun 06 '19 at 22:00
  • @Ben Thanks, that seems much similar than everything I've seen to far. I think that's what I'll end up using. – Jack Jun 06 '19 at 22:06
  • @Ruzihm, I saw that just was seeing if there was a way to simply convert a string to JSON object via C#. From what I saw, it seems to be doing the opposite in ~10 different ways. – Jack Jun 06 '19 at 22:21
  • @JackStoller Anywhere that says "Deserialize" on that page is talking about going from JSON->C# object. What you mean when you say "string to JSON object" is vague. The part where it says "Deserialize json string without class" might address that. – Ruzihm Jun 06 '19 at 22:28
  • @Ruzihm Sorry for being vague, but from what I understand they start out with a C# Class, then go to a JSON string, then using both the string and the C# Class, create a C# Object. I was wondering if you could skip the C# class and start out with just a JSON string and go to a C# Object. Thanks for the response. – Jack Jun 06 '19 at 22:41
  • @JackStoller definitely take a look at the "Deserialize json string without class" then. – Ruzihm Jun 06 '19 at 22:54

2 Answers2

2

I think closest to what you describe in your questions and the comments as

simply convert a JSON string into a JSONObject

would maybe be the good old SimpleJSON. Simply copy the SimpleJSON.cs and depending on your needs maybe SimpleJSONUnity.cs(provides some extensions for directly parsing to and from Vector2, Vector3, Vector4, Quaternion, Rect, RectOffset and Matrix4x4) somewhere into your Assets folder.

Then given the example json

{
    "version": "1.0",
    "data": {
        "sampleArray": [
            "string value",
            5,
            {
                "name": "sub object"
            }
        ]
    }
}

you can simply access single fields like

using SimpleJSON;

...

var jsonObject = JSON.Parse(the_JSON_string);

string versionString = jsonObject["version"].Value;         // versionString will be a string containing "1.0"
float versionNumber = jsonObject["version"].AsFloat;        // versionNumber will be a float containing 1.0
string val = jsonObject["data"]["sampleArray"][0];          // val contains "string value"
string name = jsonObject["data"]["sampleArray"][2]["name"]; // name will be a string containing "sub object"
...

Using this you don't have to re-create the entire c# class representation of the JSON data which might sometimes be a huge overhead if you just want to access a single value from the JSON string.


However if you want to serialze and deserialize entire data structures you won't get happy using SimpleJSON. Given the example above this is how you would use Unity's JsonUtility

Create the c# class representation of the data yu want to store. In this case e.g. something like

[Serializable]
public class RootObject
{
    public string version = "";
    public Data data = new Data();
}

[Serializable]
public class Data
{
    public List<object> sampleArray = new List<object>();
}

[Serializeable]
public class SubData
{
    public string name = "";
}

Then fill it with values and parse it to JSON like

var jsonObject = new RootObject()
    {
        version = "1.0",
        data = new Data()
            {
                sampleArray = new List<object>()
                    {
                        "string value",
                        5,
                        new SubData(){ name = "sub object" }
                    }
            }
    };

var jsonString = JsonUtility.ToJson(jsonObject);

And to convert it back to c# either if jsonObject was not created yet

jsonObject = JsonUtility.FromJson<RootObject>(jsonString);

otherwise

JsonUtility.FromJsonOverwrite(jsonString, jsonObject);
derHugo
  • 83,094
  • 9
  • 75
  • 115
0

JSON is just how objects are represented in JavaScript. While C# can use JSON, you'll probably have a much easier time defining your own custom classes. Using classes, you can define all the properties you'll need, string them together into a list, etc.. Hope this helps.

Benjamin U.
  • 580
  • 1
  • 3
  • 16