当前位置: 首页 > Web前端 > HTML5

如何将txt格式转成json格式?

时间:2023-04-04 23:33:56 HTML5

JSON是一种轻量级的数据交换格式。它基于ECMAScript的一个子集,使用完全独立于编程语言的文本格式来存储和表示数据。简单和清晰的层次结构使JSON成为一种理想的数据交换语言。便于人的读写,也便于机器解析生成,能够有效提高网络传输的效率。下面是转换后的程序代码:usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Text;usingLitJson;usingUnityEngine;usingExcel;usingExcel.Core;usingOfficeOpenXml.Style;usingOfficeOpenXml;///

///该类用于json时不能有构造函数///publicclassDataNode//自定义类,承担稍后读取的数据分类{公共字符串复制名称;公共字符串复制位置;publicstringCopyRotation;}publicclassDataCenter//自定义类包含List列表添加稍后读取的数据信息{publicListList;publicDataCenter(){List=newList();}}publicclassJsonConvert:MonoBehaviour{//初始化用这个privatestring_txtPath;//TXT文件路径privatestring_jsonPath;//转换后写入的json路径privatestring_excelPath;voidStart(){_jsonPath=Application.streamingAssetsPath+"/CopyInfo.json";//定义路径_txtPath=Application.streamingAssetsPath+"/CopyInfo.txt";_excelPath=Application.streamingAssetsPath+"/CopyInfo.json";//Json解析快网ReadTextToJson();//读取TXT文件并转为JsonReadJsonFromJsonPath();//读取Json文件WriteExcel(_excelPath);}//Update每帧调用一次voidUpdate(){}voidReadJsonFromJsonPath(){//读取所有(文件路径)stringjsondata=File.ReadAllText(_jsonPath);Listnode=JsonMapper.ToObject>(jsondata);//固定格式Debug.LogError(node.Count);}voidReadTextToJson(){DataCenterdc=newDataCenter();//实例化dc,稍后使用它的List//读取文件固定格式using(StreamReaderreader=newStreamReader(_txtPath,Encoding.UTF8)){stringtmpStr=string.空的;while(!string.IsNullOrEmpty(tmpStr=reader.ReadLine())){string[]infos=tmpStr.Split('_');DataNode_node=newDataNode();//实例化调用其属性_node.CopyName=infos[0];//赋值读取内容_node.CopyPosition=infos[1];_node.CopyRotation=信息[2];dc.List.Add(_node);//将内容添加到列表中}}//读取数据后,开始写入json传过来的List<>字符串。jsonData=JsonMapper.ToJson(dc.List);File.WriteAllText(_jsonPath,jsonData);}privatevoidWriteExcel(stringpath){DataCenterdc=newDataCenter();//实例化dc,稍后使用它的List//读取固定格式using(StreamReaderreader=newStreamReader(_txtPath,Encoding.UTF8)){stringtmpStr=字符串.空;while(!string.IsNullOrEmpty(tmpStr=reader.ReadLine())){string[]infos=tmpStr.Split('_');DataNode_node=newDataNode();//实例化调用其属性_node.CopyName=infos[0];//赋值读取内容_node.CopyPosition=infos[1];_node.CopyRotation=信息[2];dc.List.Add(_node);//添加内容到列表}}Debug.LogError(dc.List.Count);FileInfoexcelInfo=newFileInfo(路径);如果(excelInfo.Exists)新文件信息(路径);}//开始使用Excelusing(ExcelPackagepackage=newExcelPackage(excelInfo)){ExcelWorksheetsheet=package.Workbook.Worksheets.Add("TestInfo");//添加了一个工作表sheet.Cells[1,1].Value="CopyName";sheet.Cells[1,2].Value="CopyPosition";sheet.Cells[1,3].Value="CopyRotation";对于(inti=0;i