gpt4 book ai didi

c# - 如何从嵌套类或结构中以 json 格式编写

转载 作者:太空宇宙 更新时间:2023-11-03 12:00:18 24 4
gpt4 key购买 nike

将嵌套 json 文件的结构作为嵌套类,当我写入 json 时,json 始终为空。

public class Class1
{
public int level;
public float timeElapsed;
public string playerName;
public Class2 subClass;


}

public class Class2
{
public int age;
}

Class2 class2= new Class2();
class2.age = 99;

Class1 myObject = new Class1();
myObject.level = 1;
myObject.timeElapsed = 47.5f;
myObject.playerName = "Francis";
myObject.subClass = class2;

jsonString = JsonUtility.ToJson(myObject);
print(jsonString);

我得到 {"level":1,"timeElapsed":47.5,"playerName":"Francis"},年龄在哪里?!

最佳答案

using System;
using UnityEngine;

public class Example : MonoBehaviour
{
private void Start()
{
Class2 class2 = new Class2();
class2.age = 99;

Class1 myObject = new Class1();
myObject.level = 1;
myObject.timeElapsed = 47.5f;
myObject.playerName = "Francis";
myObject.subClass = class2;

var jsonString = JsonUtility.ToJson(myObject);
print(jsonString);
}
}

[Serializable]
public class Class1
{
public int level;
public float timeElapsed;
public string playerName;
public Class2 subClass;
}

[Serializable]
public class Class2
{
public int age;
}

结果是 {"level":1,"timeElapsed":47.5,"playerName":"Francis","subClass":{"age":99}}

关于c# - 如何从嵌套类或结构中以 json 格式编写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com