Home > front end >  Decode Json String in Unity C# Script
Decode Json String in Unity C# Script

Time:10-15

I am trying to decode the JSON string into a single element. Below is my code. It is returning null as a result.

var topOfHead = landmarks.Landmark[10];
string jsonString = topOfHead.ToString();
//Json in String  - tophead:{ "x": 0.8063538, "y": 0.6247897, "z": -0.0117829954 }
DistanceVector serialized = JsonUtility.FromJson<DistanceVector>(jsonString);
//Debug.Log("Headposition: "   serialized.x);

DistanceVector Class

  [SerializeField]
  public class DistanceVector{
  public double? x{get; set;}
  public double? y{get; set;}
  public double? z{get; set;}
}

serialized.x value is coming to zero in this case.

CodePudding user response:

JsonUtility in Unity follows the same serialisation rules for all objects. That means you can't natively (de)serialise such things as dictionaries. It also means you can't (de)serialise properties or nullables.

To get around this, you'd have to modify your code:

[Serializable]
public class DistanceVector
{
  public double x;
  public double y;
  public double z;
}

The class should aso be decorated with the [Serializable] attribute if you'd like to Unity to also serialise it through the Inspector.

I assume that the following comment doesn't actually include the 'tophead' string in your Json?

//Json in String  - tophead:{ "x": 0.8063538, "y": 0.6247897, "z": -0.0117829954 }

If Json DOES include 'tophead', are you able to remove it? That 'tophead' is considered an element of its own otherwise, and as such you'd need to deserialise an item that contains its own field of type DistanceVector. For example:

[Serializable]
public class Container
{
  public DistanceVector tophead;
}

var tophead = JsonUtility.FromJson<Container>(jsonString).tophead;

JsonUtility will then also require the Json format to be:

{ "tophead":{ "x": 0.8063538, "y": 0.6247897, "z": -0.0117829954 } }

The alternative is to use a different Json Serialiser such as Newtonsoft.Json or System.Text.Json (my preference).

CodePudding user response:

Don't use the "?" because it is detecting the current variable as a nullable and it returns a null value.

Instead of this public double? x{get; set;}, replace it with this public double x{get; set;}

  • Related