[Solved] converting Json to instance of struct

I mistakenly postet this under the wrong subject. Guess this fits better under “scripting”.

Hi,
I want to import the following example of a Json:

{
   "g":[
      {
         "m":"cube",
         "s":{
            "x":4,
            "y":6.75,
            "z":0.5
        },
         "p":{
            "x":-6.75,
            "y":20,
            "z":154.7
        },
         "r":{
            "x":0,
            "y":0,
            "z":90
        }
     },
      {
         "m":"cylinder",
         "s":{
            "x":4,
            "y":30,
            "z":4
        },
         "p":{
            "x":-7,
            "y":20,
            "z":149
        },
         "r":{
            "x":0,
            "y":0,
            "z":90
        }
     }
  ]
}

This is my struct:

[System.Serializable]
    public struct ProductInstance
    {
        public List<G> g;

        [System.Serializable]
        public struct G
        {
            public string m;
            public v3 s;
            public v3 p;
            public v3 r;

            [System.Serializable]
            public struct v3
            {
                public float x;
                public float y;
                public float z;
            }
        }

        public static ProductInstance CreateFromJSON(string jsonString)
        {
            return JsonUtility.FromJson<ProductInstance>(jsonString);
        }
    }

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!

Does this help perhaps?

As an alternative approach i have found this to be a good package for this kind of task:

Good luck!

Thank you! It works now.

You brought me on the right path.
I now use Newtonsoft.Json for conversion.

public class Product
        {
            public List<G> g { get; set; }
        }

        public class G
        {
            public string m { get; set; }
            public v3 s { get; set; }
            public v3 p { get; set; }
            public v3 r { get; set; }
        }

        public class v3
        {
            public double x { get; set; }
            public double y { get; set; }
            public double z { get; set; }
        }

And call the conversion with:

var prods = new List<Product>();
prods.Add(JsonConvert.DeserializeObject<Product>(myJsonString));```
1 Like