유니티로 Json 사용하기

2020. 9. 1. 14:31개발/유니티

Json 처리 클래스

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
using System;
using UnityEngine;
 
public static class JsonData
{
   [Serializable]
    public class Data<T>
    {
        public T[] array;
        public T value;
    }
 
    public static T[] FromJsonArray<T>(string json)
    {
        Data<T> data = JsonUtility.FromJson<Data<T>>(json);
        return data.array;
    }
 
    public static T FromJson<T>(string json)
    {
        Data<T> data = JsonUtility.FromJson<Data<T>>(json);
        return data.value;
    }
 
    public static string ToJson<T>(T[] array)
    {
        Data<T> Data = new Data<T>();
        data.array = array;
        return JsonUtility.ToJson(data);
    }
 
    public static string ToJson<T>(T[] array, prettyPrint)
    {
        Data<T> Data = new Data<T>();
        data.array = array;
        return JsonUtility.ToJson(data, prettyPrint);
    }
 
    public static string ToJson<T>(T[] array, bool 
}
cs
 
 
 
 
 
 

 

Json 데이터 파싱하기

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
using UnityEngine;
 
public class Product
{
    string name;
    string date;
    int    price;
}

public
 class UsingJson
{
    void UsingArrayFunction(json)
    {
        var data = JsonData.FromJsonArray<Product>(json);
 
        foreach(var products in data)
        {
            Debug.Log(Products.name);
            Debug.Log(Products.date);
            Debug.Log(Products.price.ToString());
        }
    }
 
    void UsingFunction(json)
    {
        var data = JsonData.FromJsonArray<Product>(json);
 
        Debug.Log(data.name);
        Debug.Log(data.date);
        Debug.Log(data.price.ToString());
    }
}
cs

 

입력값

1
2
3
4
5
6
7
8
9
10
11
12
"array":[
            {
                "name":"apple",
                "date":"2020-09-01",
                "price":500
            },
            {
                "name":"note",
                "date":"2020-08-11",
                "price":2000
            }
]}
cs

 

출력값

1
2
3
4
5
6
apple
2020-09-01
500
note
2020-08-11
2000
cs

 

 

ToJson은 역으로 계산되는거라고 보면 됨.