First off… you can copy your code into the forum with the code tags. Rather than doing it as images. See:
…
With that said…
That “1” is not a class, it’s a property, and the property contains an object.
What you’re asking for is the ability to deserialize properties with numeric names. But C# doesn’t support numerically named properties. So you’ll need a way to tell the serialization engine to rename the property.
So this hinges on the serialization engine you use. If you’re using the built in JsonUtility from Unity there’s not really a lot you can do. Unity technically has the ‘FormerlySerializedAs’ attribute, but it doesn’t work for your situation.
If you go and get Json.Net though, you can use the JsonProperty attribute to define the name of the property like so:
[System.Serializable]
public class APIData
{
[JsonProperty("1")]
public Maquina_Um One { get; set; }
}
Json.Net is available as a package for unity:
Newtonsoft Json Unity Package | Newtonsoft Json | 3.0.2
Here’s an example of it working for some generic json:
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Serialization;
public class zTest01 : MonoBehaviour
{
private void Update()
{
if (!Input.GetKeyDown(KeyCode.Space)) return;
var json = "{\"1\":{\"Id\":\"Test\",\"Value\":5},\"2\":{\"Id\":\"Dyldo\",\"Value\":6}}";
//var obj = JsonUtility.FromJson<Foo>(json); //does not work
var obj = JsonConvert.DeserializeObject<Foo>(json);//works
Debug.Log(obj?.One?.Id);
Debug.Log(obj?.One?.Value);
Debug.Log(obj?.Two?.Id);
Debug.Log(obj?.Two?.Value);
}
[System.Serializable]
private class Foo
{
[FormerlySerializedAs("1")]//does not work
[JsonProperty("1")]//works
public Bar One;
[FormerlySerializedAs("2")]//does not work
[JsonProperty("2")]//works
public Bar Two;
}
[System.Serializable]
private class Bar
{
public string Id;
public int Value;
}
}
Note that such a format though implies there might be a variable number of properties (1,2,3…N). It might be better to use something like a JObject to deserialize each entry: