user3277468
user3277468

Reputation: 141

Unity C# Json Read/Write

My Code is referencing https://docs.unity3d.com/ScriptReference/JsonUtility.html

Inside of my LoadJson() method is a commented out print statement to show a certain json value I know it would be

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

to show the head Value, I think my issue is the return type in method

 public static SaveCharacters CreateFromJSON(string jsonString)

But I am at a loss with Json in C# any help would be nice I haven't found any useful solutions.

Json File

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

Code

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);
}
}

Upvotes: 1

Views: 3297

Answers (1)

Qusai Azzam
Qusai Azzam

Reputation: 530

Let us Suppose that you have This Json File :

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

and you want to Get the Score Value :

First : download this Library SimpleJson

and then call it like this :

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

Upvotes: 1

Related Questions