Home > Mobile >  C#, json return empty converting from List
C#, json return empty converting from List

Time:12-07

I have script as follows but when i try to make json file, it just return empty {}

QuizData.cs

using System.Collections.Generic;

[System.Serializable]
public class QuizList
{
    public string quizName;
    public List<QuestionList> questionList = new List<QuestionList>();

    public QuizList(string quizName, List<QuestionList> questionList)
    {
        this.quizName = quizName;
        this.questionList = questionList;
    }
}

[System.Serializable]
public class QuestionList
{
    public string question;
    public List<string> choice = new List<string>();
    public int option;

    public QuestionList(string question, List<string> choice, int option)
    {
        this.question = question;
        this.choice = choice;
        this.option = option;
    }
}

datatest.cs

public class datatest : MonoBehaviour
{
    List<QuizList> quiz_list = new List<QuizList>();
    List<QuestionList> question_list = new List<QuestionList>();
    List<string> choices = new List<string>();

    void Awake()
    {
        choices.Add("Aaa");
        choices.Add("Bbb");
        choices.Add("Ccc");

        question_list.Add(new QuestionList(
            "I'm Gonna Be (500 Miles)",
            choices,
            1
        ));

        quiz_list.Add(new QuizList(
            "sadasdasd",
            question_list
        ));

        var json = JsonUtility.ToJson(quiz_list);
        Debug.Log(json); // this return empty json string `{}`

    }
}

debug output here

// Debug output
for (int i = 0; i < quiz_list.Count; i  )
{
    Debug.Log(quiz_list[i].quizName);

    foreach (var ql in quiz_list[i].questionList)
    {
        Debug.Log(ql.question);
        Debug.Log(ql.question);

        foreach (var c in ql.choice)
        {
            Debug.Log(c);
        }
    }
}

CodePudding user response:

In addition, the List must be wrapped in a class.


// Add wrapper class for List<QuizList>
[System.Serializable]
public class QuizLists
{
    public List<QuizList> lists;

    public QuizLists(List<QuizList> lists)
    {
        this.lists = lists;
    }
}

// test

using System.Collections.Generic;
using UnityEngine;

public class datatest : MonoBehaviour
{
    QuizLists quiz_list;
    List<QuestionList> question_list = new List<QuestionList>();
    List<string> choices = new List<string>();

    void Awake()
    {
        choices.Add("Aaa");
        choices.Add("Bbb");
        choices.Add("Ccc");

        question_list.Add(new QuestionList(
            "I'm Gonna Be (500 Miles)",
            choices,
            1
        ));

        quiz_list = new QuizLists(new List<QuizList>()
        {
            new QuizList(
                "sadasdasd",
                question_list
            )
        });

        var json = JsonUtility.ToJson(quiz_list);
        Debug.Log(json);

    }
}
  • Related