Json

4/3/2024 Unity3d

functions

functions parameter describe
jsonDecode(string) 1. json

return: table
decode

Return result: lua table

解码

返回结果:lua table
jsonEncode(table) 1.table or object

return: json string
encode

Return result: json string

编码

返回结果:字符串

example:

--{"tag":"test3","ids":[{"age":5,"nickname":"hello1","sex":1,"id":1},{"age":3,"nickname":"hello2","sex":1,"id":2},{"age":15,"nickname":"wang","sex":0,"id":3}],"id":5}

--方法1--
-- strData 是c# 传递过来的 json 字符串 或者是 lua中的json 字符串,
local strData=''
-- 获取json 库
local json = require("json")
-- 解码 后 jsonData 是一个lua table
local jsonData=json.decode(strData) 


--方法2--推荐--
--json 转 lua Table
local table1Data=jsonDecode(strData)

--对象转json 字符串
local jsonstr= jsonEncode(table1Data)
log(jsonstr) 



-- 输出
print(jsonData.id)
print(jsonData['id'])
print(jsonData['tag'])
log('--------------------------')
for i,v in pairs(jsonData.ids) do
    log(v.id..','..v.nickname..','..v.age..','..v.sex)
end
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

c#脚本

struct test3Data
{
    public int id;
    public string tag;
    public List<test3Data_1> ids;
}

struct test3Data_1
{
    public int id;
    public string nickname;
    public int age;
    public int sex;

    public test3Data_1(int _id, string _name, int _age, int _sex)
    {
        id = _id;
        nickname = _name;
        age = _age;
        sex = _sex;
    }
}

void Test3()
{
    test3Data data = new test3Data();
    data.id = 5;
    data.tag = "test3";
    data.ids = new List<test3Data_1>();
    data.ids.Add(new test3Data_1(1, "hello1", 5, 1));
    data.ids.Add(new test3Data_1(2, "hello2", 3, 1));
    data.ids.Add(new test3Data_1(3, "wang", 15, 0));
    
    string jsonstr = JsonConvert.SerializeObject(data);
    
    test3Data data1 = JsonConvert.DeserializeObject<test3Data>(jsonstr);
    //{"tag":"test3",
    //"ids":[{"age":5,"nickname":"hello1","sex":1,"id":1},{"age":3,"nickname":"hello2","sex":1,"id":2},{"age":15,"nickname":"wang","sex":0,"id":3}],"id":5}
}
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

lua 中写入json数据

local json_str=[[{
    "behavior":[
        {
            "id":1,
            "state":"Attack1",
            "range_min":3,
            "range_max":7,
            "animation":"attack_loop",
            "VFXOffset":"0,0,0"
        }
    ]
}]]

local data = jsonDecode(json_str)
print(data.behavior[1].state) --Attack1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Last Updated: Thu, 11 Apr 2024 06:54:22 GMT