skip to Main Content

I am trying to deserialize the same object I serialized to Firebase Realtime database but am running into an issue getting it to work. Here’s the class/script breakdown:

[Serializable]
public class PuzzleSphereTarget
{
    public Nullable<float> x;
    public Nullable<float> y;
    public Nullable<float> z;

    public PuzzleSphereTarget()
    {
        this.x = null;
        this.y = null;
        this.z = null;
    }
    public PuzzleSphereTarget(float xParam, float yParam, float zParam)
    {
        this.x = xParam;
        this.y = yParam;
        this.z = zParam;
    }

    public string ToJson()
    {
        return JsonUtility.ToJson(this);
    }

}

As well as a wrapper PuzzleSphereInformation class:

[Serializable]
public class PuzzleSphereInformation
{
    public string creatorName { get; set; }
    public List<PuzzleSphereTarget> puzzleSphereTarget { get; set; }

    public PuzzleSphereInformation()
    {
        this.creatorName = null;
        this.puzzleSphereTarget = new List<PuzzleSphereTarget>();
    }
    public PuzzleSphereInformation(string creatorName, List<PuzzleSphereTarget> puzzleSphereTarget)
    {
        this.creatorName = creatorName;
        this.puzzleSphereTarget = puzzleSphereTarget;
    }

    public string ToJson()
    {
        return JsonUtility.ToJson(this);
    }

}

How I’m saving:

// creatorName: string, puzzleTargets: List<PuzzleSphereTarget>
private void SavePuzzle(creatorName, puzzleTargets)
    PuzzleSphereInformation puzzleInfo = new PuzzleSphereInformation(creatorName, puzzleTargets);
    string puzzleInfoJson = JsonConvert.SerializeObject(puzzleInfo);
    FirebaseDatabase.DefaultInstance.GetReference($"/community_puzzles/").Push().SetRawJsonValueAsync(puzzleInfoJson);
}

Object in fireBase:
{"creatorName":"test user","puzzleSphereTarget":[{"x":-0.2674436,"y":0.009597826,"z":0.894937754},{"x":0.2539144,"y":0.00647806656,"z":0.8653086}]}

When I try to deserialize the same object, it’s blank and I don’t know why (this is the correct firebase db layer to retrieve the data):

_databaseReference.GetValueAsync().ContinueWithOnMainThread(task =>
{
    //// omitted firebase code ////
            foreach (DataSnapshot targetInfo in targetSnapshot.Children)
            {
                string puzzleDataJson = targetInfo.GetRawJsonValue();
                PuzzleSphereInformation puzzleInformation = JsonConvert.DeserializeObject<PuzzleSphereInformation>(puzzleDataJson);
                Debug.Log("creatorName" + puzzleInformation.creatorName); // nothing
            }
    //// omitted fb code////
});

What am I doing wrong in this case? I am trying to deserialize the same object I serialized and no luck. Thx for any help

I’ve tried JsonUtility.FromJson, JsonConvert and neither has worked.

2

Answers


  1. Chosen as BEST ANSWER

    I looked again at deserializing part and found a fix! Turns out instead of targetSnapshot.GetRawJsonValue() what I needed was: targetSnapshot.Value.ToString() then the deserialization worked fine


  2. It looks like your deserialization issue is due to a mismatch between the JSON structure stored in Firebase and the way you’re trying to deserialize it. Here’s a short breakdown of what might be going wrong and how to fix it:

    1. JSON Format and Serialization

      • You’re using JsonConvert.SerializeObject to save data, but then trying to deserialize with JsonConvert.DeserializeObject. Make sure you’re consistent with the same method for both serialization and deserialization. Since you used JsonConvert, stick with it for deserialization.

    For example:

    • You’re using JsonConvert.SerializeObject to save data to Firebase. When deserializing, you should use JsonConvert.DeserializeObject to match. If you switch to JsonUtility for deserialization, ensure that both the serialization and deserialization methods are consistent. Mismatched methods can lead to issues. Since you used JsonConvert for serialization, stick with it for deserialization.
    1. JSON Structure

      • Check that the JSON structure exactly matches your C# classes. Any mismatch, especially with lists and nullable types, can cause issues.
    2. Nullable Types

      • You’re using Nullable<float> for x, y, and z. This should work fine, but double-check that the JSON correctly reflects this.

    Here’s a revised approach for deserialization to help ensure everything is being read correctly:

    _databaseReference.GetValueAsync().ContinueWithOnMainThread(task =>
    {
        if (task.IsFaulted)
        {
            Debug.LogError("Failed to retrieve data: " + task.Exception);
            return;
        }
        
        DataSnapshot snapshot = task.Result;
        foreach (DataSnapshot targetSnapshot in snapshot.Children)
        {
            string puzzleDataJson = targetSnapshot.GetRawJsonValue();
            PuzzleSphereInformation puzzleInformation = JsonConvert.DeserializeObject<PuzzleSphereInformation>(puzzleDataJson);
            if (puzzleInformation != null)
            {
                Debug.Log("creatorName: " + puzzleInformation.creatorName);
                // Optional: Print PuzzleSphereTargets for verification
                foreach (var target in puzzleInformation.puzzleSphereTarget)
                {
                    Debug.Log($"Target - x: {target.x}, y: {target.y}, z: {target.z}");
                }
            }
            else
            {
                Debug.LogError("Deserialization returned null.");
            }
        }
    });
    

    Further

    • Make sure your Firebase path (/community_puzzles/) is correct and that there’s data present.
    • Confirm that your PuzzleSphereInformation class matches the JSON structure perfectly.
    • Check console logs for any errors or issues when fetching or parsing data.

    I hope this helps to fix your deserialization problem.

    Regards,
    Konan

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search