Unity C# Json Read/Write

Unity C# Json Read/Write

我的代码引用了https://docs.unity3d.com/ScriptReference/JsonUtility.html

我的 LoadJson() 方法内部是一条注释掉的打印语句,用于显示某个 json 值,我知道它是

x["Character0"]["Head"].ToString()

显示头部值,我认为我的问题是 return 类型方法

 public static SaveCharacters CreateFromJSON(string jsonString)

但我对 C# 中的 Json 感到茫然,任何帮助都很好我还没有找到任何有用的解决方案。

Json 文件

{
"Character0":{
    "Head":"HeadCube",
    "Neck":"NeckCube",
    "Body":"BodyCube",
    "Arms":"Sphere_Capsule_Arms",
    "Legs":"Sphere_Capsule_Legs"
    }
}

代码

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

[System.Serializable]
public class SaveCharacters
{
private string json;
private string Head, Neck, Body, Arms, Legs;

private static SaveCharacters _Instance;

public static SaveCharacters Instance { get { return _Instance; } }
void Awake() {
    if (_Instance != null)
    {
        _Instance = this;
    }
}
// Start is called before the first frame update
public void starts()
{
    LoadJson();
}

private void LoadJson()
{
    using (StreamReader r = new StreamReader("Assets/JSON/CustomCharacters.json"))
    {
        json = r.ReadToEnd();
        Debug.Log(json);
        SaveCharacters x =CreateFromJSON(json);

        //Debug.Log(x[""][""]);
    }
}
public void Load(string savedData)
{
    JsonUtility.FromJsonOverwrite(savedData, this);
}
public string SaveToString()
{
    return JsonUtility.ToJson(this);
}
public static SaveCharacters CreateFromJSON(string jsonString)
{
    return JsonUtility.FromJson<SaveCharacters>(jsonString);
}
}

让我们假设您有这个 Json 文件:

{
  "Player": {
    "Score": 1
  },
  "Teams":{
    "Levels": {
      "Level": 1
    }
  }
}

并且您想获得分值:

首先:下载这个库SimpleJson

然后这样称呼它:

JSONNode node = JSON.Parse( jsonString );
string score = node["Player"]["Score"].Value;