Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

converting Json to object of struct

Discussion in 'AR/VR (XR) Discussion' started by Gerray2, Jan 22, 2020.

  1. Gerray2

    Gerray2

    Joined:
    Apr 24, 2018
    Posts:
    13
    Hi,
    I want to import the following example of a Json:
    Code (CSharp):
    1. {
    2.    "g":[
    3.       {
    4.          "m":"cube",
    5.          "s":{
    6.             "x":4,
    7.             "y":6.75,
    8.             "z":0.5
    9.         },
    10.          "p":{
    11.             "x":-6.75,
    12.             "y":20,
    13.             "z":154.7
    14.         },
    15.          "r":{
    16.             "x":0,
    17.             "y":0,
    18.             "z":90
    19.         }
    20.      },
    21.       {
    22.          "m":"cylinder",
    23.          "s":{
    24.             "x":4,
    25.             "y":30,
    26.             "z":4
    27.         },
    28.          "p":{
    29.             "x":-7,
    30.             "y":20,
    31.             "z":149
    32.         },
    33.          "r":{
    34.             "x":0,
    35.             "y":0,
    36.             "z":90
    37.         }
    38.      }
    39.   ]
    40. }

    This is my struct:

    Code (CSharp):
    1. [System.Serializable]
    2.     public struct ProductInstance
    3.     {
    4.         public List<G> g;
    5.  
    6.         [System.Serializable]
    7.         public struct G
    8.         {
    9.             public string m;
    10.             public v3 s;
    11.             public v3 p;
    12.             public v3 r;
    13.  
    14.             [System.Serializable]
    15.             public struct v3
    16.             {
    17.                 public float x;
    18.                 public float y;
    19.                 public float z;
    20.             }
    21.         }
    22.  
    23.         public static ProductInstance CreateFromJSON(string jsonString)
    24.         {
    25.             return JsonUtility.FromJson<ProductInstance>(jsonString);
    26.         }
    27.     }
    And this is how I call it inside a function:

    var pi = ProductInstance.CreateFromJSON(json);


    But all I get is a exception. "ArgumentException: JSON parse error: The document root must not follow by other values."

    Please help!