Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Possible to SerializeDeserialize JSON with Job?

Discussion in 'Entity Component System' started by bsterling250DI, May 13, 2020.

  1. bsterling250DI

    bsterling250DI

    Joined:
    Sep 25, 2014
    Posts:
    78
    Hello,

    My app requests some data from web api's and gets json strings as response.

    I'd like to see if I can get any performance benefits from doing the Deserialization from inside a job.

    I would try and Deserialize the string into a struct, but the results have some nested objects I need.

    ex:
    Code (CSharp):
    1. {
    2.     "name": "Joe",
    3.     "stuff": [
    4.         {
    5.             "thing": {},
    6.             "otherThing": 1
    7.          },
    8.          {
    9.             "thing": {
    10.                 "someBool": false
    11.             },
    12.             "otherThing": 2
    13.          },
    14.     ]
    15. }
    While the root object I can make a struct and make the name a NativeString32, the "stuff" object, needs to be a NativeArray<Stuff> and even if Stuff is also a struct with value types, because it needs to be a NativeArray it isn't blittable and thus can't run on a job thread with .Schedule

    So i'm looking for suggestions on best practice.

    Should I just give up on having a BurstCompiled job to do this deserialization? I imagine Unity has to do some serialization/deserialization from the ConvertGameObject flow, so maybe they've figured out a way?
     
  2. bsterling250DI

    bsterling250DI

    Joined:
    Sep 25, 2014
    Posts:
    78
    Really? nobody has any thoughts? This really surprises me.
     
    BackgroundMover likes this.
  3. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    3,984
    I'm not understanding your logic here. You can use NativeArrays in jobs fine. Are you looking to use an existing JSON library or write your own Burst-compatible library?
     
  4. BrendonSmuts

    BrendonSmuts

    Joined:
    Jun 12, 2017
    Posts:
    86
    Deserialize JSON in a job is easy enough. Doing it with burst? Not unless you want to spend the time writing a deserializer in pure HPC#. Unity will probably get around to doing this one day anyway so I’m not sure I’d waste my time. As for the job part you should look into GCHandles. Once you create a GCHandle to a managed object (string, json deserializer, deserialized type, etc) you pass that handle in and out of jobs no problem. Cast the GCHandle target back to the type you know it is and use it as you normally would in managed code. Of course all job system safety gets throw out the window when you do this so take care in how you use this.
     
    WAYNGames likes this.