简体   繁体   中英

Unity Serializing object to Json

I'm trying to simply serialize a object into json in Unity. I have found several articles on this topic but nothing seems to be working. It is not throwing a exception directly but it is not converting the object to a json string. I have researched the pretty heavily and tried various samples. I'm not sure if the issue is the class or the logic calling the convert to json. I can easily convert using .net but this is for Unity in MonoScript, so the process seems to be a little different. I assume when you convert the object to json string it should not list the base as "null". Its also passing in a empty json string after conversion.

在此处输入图片说明

User LogIn Class:

    using UnityEngine;
using System.Collections;
using System;

[Serializable]
public class UserLogIn : MonoBehaviour
{
    public string Email;
    public string Password;
}

Here is my code in unity script:

private UserLogIn _LogIn = new UserLogIn();

    public void SetText(string text)
    {
        //[SerializeField]
        //UserLogIn _LogIn = new UserLogIn();
    //WhiteBoxGamingTestRequest();  
    _LogIn.Email = "testemail@gmail.com";
        _LogIn.Password = "12345";
        string json = JsonUtility.ToJson(_LogIn);
        Debug.Log(json);

        //User_LogIn(_login);

        //text = _bolResponse.ToString();
        //Text txt = transform.Find("Text").GetComponent<Text>();
        //txt.text = text;       
    }

I've tried this: Serialize and Deserialize Json and Json Array in Unity

seems to not work still. Looking for suggestions or corrections.

After conversion json = {} it should be a string containing values. Is Unity's json converter broken?

Conversion: 在此处输入图片说明

I finally found the answer. In order to make a object in Unity that's convertable to json it appears it needs to be a regular c# object. I'm not sure why you can't use Mono Behavior but that appears to be the problem in my class. So I hope this helps someone else in the future because Unity website was about as clear as mud.

    [System.Serializable]
public class UserLogIn
{
    public string Email;
    public string Password;
}

This is what the json string should look like once converted:

{"Email":"testemail@gmail.com","Password":"12345"}

Also wanted to give credit to this video around 7:43 into it, you can start to see the conversion process https://youtu.be/oJrAT8L4BrA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM