M语言(一)——生成json文件

 举个例子,这是我们要生成的json文件的内容

{
    "vcp_info":{
        "system_info":{
            "system":{
                "type":"controller"
            },
            "mcu_network_info":{
                "network":{
                    "ip":"10.32.6.167",
                    "ip_mask": "255.255.255.0",
                    "gate_way": "10.32.6.1",
                    "mac": "52:54:00:c9:18:70"
                }
            }
        },
        "interface_info":[
            {
                "type": "can",
                "src_ip": "0",
                "src_port": "56000",
                "dst_ip": "225.0.0.37",
                "dst_port": "56001",
                "protocol": "multicast",
                "id": "1",
                "channels": "1"
            },
            {
                "type": "adc",
                "src_ip": "0",
                "src_port": "12349",
                "dst_ip": "192.168.100.200",
                "dst_port": "12349",
                "protocol": "tcp",
                "id": "0",
                "channels": "10"
            }
        ]
    }

}

我们可以发现json数据的格式为层层嵌套的类似于字典类型的数据

实现思路:需要在Matlab中构建struct类型的数据,然后使用jsonencode将数据转化为json数据。

我们在Matlab里尝试构建struct数据

 1.构建struct数据

1.1 创建一对数据

 a=struct("type","controller")

创建了包含一对数据的struct结构

1.2创建多对数据

b=struct("ip","10.32.6.167","ip_mask", "255.255.255.0","gate_way", "10.32.6.1","mac", "52:54:00:c9:18:70")

1.3stuct的嵌套

 c=struct("network",struct("ip","10.32.6.167"))

2.jsonencode

3.[  ]的处理

在json文件中有一段为

"interface_info":[
            {
                "type": "can",
                "src_ip": "0",
                "src_port": "56000",
                "dst_ip": "225.0.0.37",
                "dst_port": "56001",
                "protocol": "multicast",
                "id": "1",
                "channels": "1"
            },
            {
                "type": "adc",
                "src_ip": "0",
                "src_port": "12349",
                "dst_ip": "192.168.100.200",
                "dst_port": "12349",
                "protocol": "tcp",
                "id": "0",
                "channels": "10"
            }
]

首先创建structcan和structadc

然后组成数组str=[structcan,structadc]

再处理外层的struct:interface_info=struct("interface_info",{str})

通过上面的方法即可生成json文件内容

4.选择文件存储路径

[fileName, pathName] = uiputfile({'*.json', 'json Files(*.json)'},'Select a path to store the json file');

 选择存储路径后就会返回两个参数:filename为文件名,pathname为路径

path=[pathName fileName];

二者合在一起为完整的路径

5.写入文件

fileID=fopen(path,'w');
fprintf(fileID,'%s\n',Text);
fclose(fileID);

通过路径打开文件,将json数据写入到文件中,然后关闭文件

6.文件检查

在properties中,通过isfile对该路径下的文件进行检查,如果文件存在result=1,文件不存在result=0。

如果文件不存在就弹出报警框,程序运行终止

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值