유니티 JSON 저장과 불러오기

Json 라이브러리 다운

유니티에서 Jsonutility 를 지원하지만 , 클래스만 json으로 변경가능 하다는 단점이 있음

LitJson 

https://litjson.net/

 

LitJSON - Home

What is LitJSON? A .Net library to handle conversions from and to JSON (JavaScript Object Notation) strings. LitJSON is written in C#, and it’s intended to be small, fast and easy to use. It's quick and lean, without external dependencies. Just a few cla

litjson.net

newtonsoft.json ::에셋 스토어에서도 구매 가능

https://www.newtonsoft.com/json

 

Json.NET - Newtonsoft

× PM> Install-Package Newtonsoft.Json or Install via VS Package Management window. ZIP file containing Json.NET assemblies and source code: Json.NET

www.newtonsoft.com

https://assetstore.unity.com/packages/tools/input-management/json-net-converters-simple-compatible-solution-58621

 

Json.NET Converters - Simple compatible solution | 입출력 관리 | Unity Asset Store

Get the Json.NET Converters - Simple compatible solution package from Wanzyee Studio and speed up your game development process. Find this & other 입출력 관리 options on the Unity Asset Store.

assetstore.unity.com


 스크립트를 하나 생성하여 다운로드한  스크립트를 선언해 줍니다

using Newtonsoft.Json;

 

class -> Json으로 변경하기

class people
{
    public string name;
    public int age;

    public people(string name, int age)
    {
        this.name = name;
        this.age = age;
    }
}

 

다음과 같이 people 클래스를 만들어주고 MonoBehaviour 안에 people 클래스의 객체를 생성해 준다

JsonConvert.SerializeObject(객체)

JsonConvert를 사용해 클래스를 Json의 형태로 변경해 주고 , 변경해 준 jData를 출력해 줍니다

public class SLManager : MonoBehaviour
{
 people p1 = new people("John Doe", 15);

 private void Start()
 {
     string jData= JsonConvert.SerializeObject(p1);
     print(jData);
 }
}

Json의 형태로 변경됨

 


리스트 <스트링, 클래스> json으로 변경하기

리스트를 사용하기 위해서 상단에 다음과 같이 선언을 해줬습니다

using System.Collections.Generic;
using Newtonsoft.Json;

 

그다음 Add를 사용해 리스트에 데이터 객체를 추가해 줍니다

List<people> data = new List<people>();

private void Start()
{
    data.Add(new people("John Doe1", 10));
    data.Add(new people("John Doe2", 20));
    data.Add(new people("John Doe3", 30));

    string jData = JsonConvert.SerializeObject(data);
    print(jData);
}

딕셔너리 <스트링, 클래스> json으로 변경하기

Dictionary<string, people> data = new Dictionary<string, people>();
private void Start()
{
    data["p1"] = new people("John1", 15);
    data["p2"] = new people("John2", 25);
    data["p3"] = new people("John3", 35);
    string jData = JsonConvert.SerializeObject(data);
    print(jData);
}

딕셔너리 <스트링, 자료형> json으로 변경하기

Dictionary<string, int> data = new Dictionary<string, int>();
private void Start()
{
    data["john1"] = 10;
    data["john2"] = 25;
    data["john3"] = 30;
    string jData = JsonConvert.SerializeObject(data);
    print(jData);
}


JSON으로 저장 & 불러오기

 

처음에 다음과 같이 리스트 안에 데이터를 넣어주었다

List<people> data = new List<people>();

private void Start()
{
    data.Add(new people("철수",15));
    data.Add(new people("유리",21));
    data.Add(new people("맹구",19));
}

 

using System.IO ;//파일로 뽑기 위해 선언

 

저장하기

public void _save()
{
   //리스트를 Json 형식으로 변경함
   string jdata = JsonConvert.SerializeObject(data);
   File.WriteAllText(Application.dataPath + "/파일명.json", jdata);
}

저장하기 버튼 클릭시, json 생성

 

불러오기

public void _load()
{
    string jdata = File.ReadAllText(Application.dataPath + "/파일명.json");
    tx.text = jdata; //받아온 데이터를 TextUI에 뿌려줌
}

 

불러오기 버튼 클릭 시

 

불러오기 버튼을 누르면 기존에 있던 데이터를 가져올 수 있고, 데이터에  접근도 가능하게 된다

public void _load()
{
    string jdata = File.ReadAllText(Application.dataPath + "/SLManager.json");
    tx.text = jdata; //받아온 데이터를 TextUI에 뿌려줌
    data = JsonConvert.DeserializeObject<List<people>>(jdata);
    print(data[0].name);
}

저장된 데이터의 값을 가져옴


암호화 시키기

public void _save()
{
    //리스트를 Json 형식으로 변경함
    string jdata = JsonConvert.SerializeObject(data);
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jdata);
    string format = System.Convert.ToBase64String(bytes); 
    File.WriteAllText(Application.dataPath + "/SLManager.json", format);
}
public void _load()
{
    string jdata = File.ReadAllText(Application.dataPath + "/SLManager.json");
    byte[] bytes = System.Convert.FromBase64String(jdata);
    string reformat = System.Text.Encoding.UTF8.GetString(bytes);
    
    tx.text = reformat; //받아온 데이터를 TextUI에 뿌려줌
    data = JsonConvert.DeserializeObject<List<people>>(reformat);
}