Home > Blockchain >  Convert json array to int array in Unity
Convert json array to int array in Unity

Time:11-09

I get a json file from a server in my Unity script. The json file looks like this.

{
  "drones": [
    [
      0.0,
      0.0,
      0.0,
      1.0,
      0.0,      
    ],
    [
      0.0,
      0.0,
      1.0,
      1.0,
      0.0,
      
    ],
    [
      0.0,
      0.0,
      1.0,
      0.0,
      0.0,
      
    ]]
}

My method reads the data stream and converts it to a json format

 String incoming_data = reader.ReadLine();
 if(incoming_data != null)
 {
      JObject json = JObject.Parse(incoming_data);
 }

But now I want to store the values ​​of "drones" in a 2D int array. How would I do that?

Is there already a parser that can convert the values? Or am I already using JObject.Parse(incoming_data) incorrectly?

CodePudding user response:

just deserialize after parsing

int[][] drones= JObject.Parse(incoming_data)["drones"].ToObject<int[][]>();

CodePudding user response:

In your json object your drones is a JArray of Jarray of int. That means you can make it an int array thus:

var intArray = json["drones"].ToObject<int[][]>(); 
  • Related