Home > Back-end >  Cannot serialize object from JSON using Unity's JsonUtilty when the object contains more object
Cannot serialize object from JSON using Unity's JsonUtilty when the object contains more object

Time:08-30

So I have an API set up that returns a JSON. The response looks as follows:

{
    "success": true,
    "results": 1,
    "data": [
        {
            "location": {
                "type": "Point",
                "coordinates": [
                    -83.338322,
                    42.705647
                ],
                "formattedAddress": "Some adress",
                "city": "SomeCity",
                "state": "STATE",
                "zipcode": "000000",
                "country": "US"
            },
            "_id": "630ce2c5a963f97ddae7387f",
            "title": "Node Developer",
            "description": "Must be a full-stack developer, able to implement everything in a MEAN or MERN stack paradigm (MongoDB, Express, Angular and/or React, and Node.js).",
            "email": "[email protected]",
            "address": "someADress",
            "company": "Company Ltd",
            "industry": [
                "Information Technology"
            ],
            "jobType": "Permanent",
            "minEducation": "Bachelors",
            "positions": 2,
            "experience": "No Experience",
            "salary": 155000,
            "lastDate": "2022-09-05T15:41:44.912Z",
            "user": "630cdf34b2bc6356a75ec29c",
            "postingDate": "2022-08-29T16:01:09.707Z",
            "slug": "node-developer"
        }
    ] }

And I am trying to serialize it as an object in C# using the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class test : MonoBehaviour
{
    public string domain = "http://localhost:3000/api/v1";
    public string request = "/jobs";

    private bool coroutineRunning = false;

    Request req;

    private void Start()
    {
        req = new Request();
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && !coroutineRunning)
        {
            StartCoroutine(GetRequest(domain   request));
        }
    }

    IEnumerator GetRequest(string uri)
    {
        coroutineRunning = true;

        UnityWebRequest request = UnityWebRequest.Get(uri);

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            string jsonText = request.downloadHandler.text;

            Debug.Log(jsonText);

            SetUpObject(jsonText);
        }
        else
        {
            Debug.LogError(request.result);
        }

        coroutineRunning = false;
    }

    void SetUpObject(string json)
    {
        req = JsonUtility.FromJson<Request>(json);

        Debug.Log(JsonUtility.ToJson(req, true));

        Debug.Log(req);
    }
}

The Request class:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class Data
{
    public Location location { get; set; }
    public string _id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public string email { get; set; }
    public string address { get; set; }
    public string company { get; set; }
    public string[] industry { get; set; }
    public string jobType { get; set; }
    public string minEducation { get; set; }
    public int positions { get; set; }
    public string experience { get; set; }
    public int salary { get; set; }
    public DateTime lastDate { get; set; }
    public string user { get; set; }
    public DateTime postingDate { get; set; }
    public string slug { get; set; }
}

[Serializable]
public class Location
{
    public string type { get; set; }
    public double[] coordinates { get; set; }
    public string formattedAddress { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string zipcode { get; set; }
    public string country { get; set; }
}
[Serializable]
public class Request
{
    public bool success { get; set; }
    public int results { get; set; }
    public Data[] data { get; set; }
}

The problem is that I can't figure out how I should create a class that can get serialized with this JSON. This API is from a course I took on creating API's and won't be used in a project, I am just trying to figure out how to properly use serialization with complex JSONs such as this one.

The request returns a string that is the JSON written above. I used that JSON format and JSON2CSHARP to generate the Request class (i know it should be called the result class). Now when I copied the generated class I swapped every List<T> with an array of that type. I also think that using Datetime instead of string and other type mismatches could be the source of the problem, but even if they were the JsonUtilty would've still populated the Success and Results fields of the Request class and left the Data as an empty array

CodePudding user response:

From the Unity documentation, I see the following (emphasis added):

Fields of the object must have types supported by the serializer. Fields that have unsupported types, as well as private fields or fields marked with the NonSerialized attribute, will be ignored.

Based on that description, and the example provided, it looks like it may only work with fields and not properties. I would try to make everything a member variable instead of a property and see if that fixes it.

  • Related