Receiving Json object over UDP

Hello, I am trying to receive Json object over UDP where Json object is sent as bytes. I already tested that Unity successfully receives the message sent.

My Json object looks like this:

{
       "obj1": {
              "Type": "Enemy",
              "posX": "10",
              "posY": "1",
              "posZ": "20",
              "rotX": "0",
              "rotY": "0",
              "rotZ": "0"
       },
       "obj2": {
              "Type": "Civilian",
              "posX": "23",
              "posY": "0.75",
              "posZ": "15",
              "rotX": "0",
              "rotY": "0",
              "rotZ": "0"
       }
}

What I want to do is

  1. Parse this and
  2. Instantiate these objects.

How can I save this? I have the following serializable class:

[System.Serializable]
public class NewSpecInfo{
    public string objectType;
    public float posX;
    public float posY;
    public float posZ;
    public float rotX;
    public float rotY;
    public float rotZ;
    // Add more variables that goes into spec in newScenario(spec)
  
    public static NewSpecInfo CreateFromJSON(string jsonString){
        return JsonUtility.FromJson<NewSpecInfo>(jsonString);
    }
}

I checked How to read .json file but mine is in different format and I have hard time dealing with (it is my first time dealing with json and also new to Unity…). Thanks in advance, and sorry if my question is not clear…

1 Like

Two things: First I think it has to go in a larger single structure, perhaps with a list of those items.

Second thing: lots of problems with Unity “tiny lite” built-in JSON:

I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes.

Instead grab Newtonsoft JSON .NET off the asset store for free, as it is way better.

PS: for folks howling about how it will “add too much size” to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work.

1 Like

I want to expand on this point – if you’re using Unity’s JSONUtility class, you’re operating by the same rules and limitations as the rest of Unity’s serialization. If you know how to operate in that sphere, you shouldn’t have any trouble using JSONUtility. Serialized classes/structs will even call ISerializationCallbackReciever methods.

If you want to gracefully handle any of the cases that Unity’s serialization fails on, like the aforementioned Dictionaries and Hashes, then Json.NET is the way to go.

To answer the OP’s question, Unity doesn’t really have a good way of dealing with arbitrary object properties. This is a good application of Json.NET, in which you can iterate over arbitrary object keys.

2 Likes