CocosCreator中,读取json

假设要读取的json数据的形式如下

{
    "TestCfg": [{
        "Id": 1,
        "Age": 1,
        "TestA": "测试1",
        "TestB": "测试11",
        "TestC": "测试111"
    }, {
        "Id": 2,
        "Age": 2,
        "TestA": "测试2",
        "TestB": "测试22",
        "TestC": "测试222"
    }]
}

首先定义json对象对应的接口,以便解析它。

interface ITestCfg
{ 
    TestCfg: ITestCfgElement[];
}
interface ITestCfgElement
{ 
    Id: number;
    Age: number;
    TestA: string;
    TestB: string;
    TestC: string;
}

读取json的示意:TestJson.ts


image.png
import { _decorator, Component, Node, JsonAsset } from 'cc';
const { ccclass, property } = _decorator;

interface ITestCfg
{ 
    TestCfg: ITestCfgElement[];
}
interface ITestCfgElement
{ 
    Id: number;
    Age: number;
    TestA: string;
    TestB: string;
    TestC: string;
}


@ccclass('TestJson')
export class TestJson extends Component 
{
    @property({visible:true})
    private _jsonAsset: JsonAsset = new JsonAsset();
    start()
    {
        this.init();
    }

    onDestroy()
    { 
        this.myDestroy();
    }

    update(deltaTime: number)
    {
        
    }
    
    private init(): void
    {
        const data = this._jsonAsset.json as ITestCfg;
        console.info('测试:' + data.TestCfg[0].TestA);
    }
    
    private myDestroy(): void
    { 

    }
}

参考内容

Excel转json

该表格可通过上述链接转为上面示意中的json

json格式化和校验

推荐阅读更多精彩内容