[유니티] Simple Save & Load Json

안녕하세요 UnityBeginner입니다.
이번글엔 Json을 활용하여 데이터를 
저장하고 불러오는 간단한 방법에대해 소개하도록 하겠습니다.


LitJson dll 파일 



우선 LitJson dll 파일을 다운로드 받고 해당 폴더에 위치시킵니다.


스크립트 JsonManager


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using LitJson;

public class JsonManager : MonoBehaviour
{
    public List<int> numArray = new List<int>();

    private void Start() {
        CreateFolder();
        SaveJsonData();
    }

    public void Update() {
        if(Input.GetKeyDown(KeyCode.F8)) {
            LoadJsonData();
        }
    }

    // Create Folder
    private void CreateFolder() {
        if (!Directory.Exists(Application.persistentDataPath + "/Json")) {
            Directory.CreateDirectory(Application.persistentDataPath + "/Json");
        }

        if (!Directory.Exists(Application.persistentDataPath + "/Log")) {
            Directory.CreateDirectory(Application.persistentDataPath + "/Log");
        }
    }

    // Json Save
    private void SaveJsonData() {

        try {
            if(numArray.Count > 0) {
                JsonData jsonData = JsonMapper.ToJson(numArray);
                File.WriteAllText(Application.persistentDataPath + "/Json/JsonData.json", jsonData.ToString());
            }

        } catch (Exception e) {
            File.WriteAllText(Application.persistentDataPath + "/Log/JsonDataSaveLog.txt", e.ToString());
        }
    }

    // Json Load
    private void LoadJsonData() {
        try {

            if (File.Exists(Application.persistentDataPath + "/Json/JsonData.json")) {

                string jsonFile = File.ReadAllText(Application.persistentDataPath + "/Json/JsonData.json");
                JsonData jsonData = JsonMapper.ToObject(jsonFile);

                for (int i = 0; i < jsonData.Count; i++) {
                    Debug.Log("jsonData["+i+"] : " + jsonData[i].ToString());
                }
            }

        } catch (Exception e) {
            File.WriteAllText(Application.persistentDataPath + "/Log/JsonDataLoadLog.txt", e.ToString());
        }

    }


}

Json을 활용한 간단한 Save Load 예제입니다.

JsomMapper 오브젝트를 Json 변환시키고 특정경로에 File Text로 변환하여
기록시켜놓고 필요한 시점에 불러들여 다시 Json형태로 변환하여 
결과값을 불러들입니다.

배열에 미리 값을 기록하여 스크립트가 활성화되면 세이브가 진행되며
F8키를 입력 받을 때 저장되어있는 데이터들을 확인하는 코드입니다.

Save = 배열값 > JsonData 변환 > string 변환 > Text File저장
Load = TextFile 값 > JsonData 변환 > string변환 > Console 출력


Inspector 배열 값



심플한 예제로 Int형 배열만 진행하였지만 
다양한 타입을 활용하여 저장, 불러오기가능합니다.

Console 출력 창



파일안의 저장되어있는 데이터를 읽어 console창에 출력한 결과입니다.

영상 결과화면



댓글