国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Unity數(shù)據(jù)解析(Json、XML、CSV、二進(jìn)制)

這篇具有很好參考價(jià)值的文章主要介紹了Unity數(shù)據(jù)解析(Json、XML、CSV、二進(jìn)制)。希望對大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

注釋

常見的數(shù)據(jù)解析(Json、XML、CSV、二進(jìn)制)文章來源地址http://www.zghlxwxcb.cn/news/detail-832578.html

using System;
using System.IO;
using System.Xml.Serialization;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// 數(shù)據(jù)解析(Json、XML、CSV、二進(jìn)制)
/// </summary>
public class AnalyticData
{
    #region Json
    /// <summary>
    /// Json序列化接口
    /// </summary>
    /// <typeparam name="T">泛型類</typeparam>
    /// <param name="dataClass">序列化對象</param>
    /// <returns></returns>
    public static string JsonSerialization<T>(T dataClass) where T : class
    {
        string jsonStr = JsonConvert.SerializeObject(dataClass);
        return jsonStr;
    }

    /// <summary>
    /// Json反序列化接口
    /// </summary>
    /// <typeparam name="T">泛型類</typeparam>
    /// <param name="path">文件路徑</param>
    /// <returns></returns>
    public static T JsonRead<T>(string path) where T : class
    {
        T Data;
        StreamReader sr = new StreamReader(path);
        string jsonStr = sr.ReadToEnd();
        //反序列化
        Data = JsonConvert.DeserializeObject<T>(jsonStr);
        return Data;
    }

    /// <summary>
    /// Json反序列化接口(數(shù)組類型)
    /// </summary>
    /// <typeparam name="T">泛型類</typeparam>
    /// <param name="path">文件路徑</param>
    /// <returns></returns>
    public static T[] JsonArrayRead<T>(string path) where T : class
    {
        T[] DataArray;
        StreamReader sr = new StreamReader(path);
        string jsonStr = sr.ReadToEnd();
        //反序列化
        DataArray = JsonConvert.DeserializeObject<T[]>(jsonStr);
        return DataArray;
    }

    /// <summary>
    /// Json反序列化接口
    /// </summary>
    /// <typeparam name="T">泛型類</typeparam>
    /// <param name="str">需解析字符串</param>
    /// <returns></returns>
    public static T JsonByStringRead<T>(string str) where T : class
    {
        T Data;
        //反序列化
        Data = JsonConvert.DeserializeObject<T>(str);
        return Data;
    }
    #endregion

    #region XML
    /// <summary>
    /// XML序列化接口
    /// </summary>
    /// <typeparam name="T">泛型類</typeparam>
    /// <param name="dataClass">序列化對象</param>
    /// <returns></returns>
    public static string XMLSerialization<T>(T dataClass) where T : class
    {
        using (StringWriter sw = new StringWriter())
        {
            //此處T必須是Public類型
            Type t = dataClass.GetType();
            XmlSerializer serializer = new XmlSerializer(dataClass.GetType());
            serializer.Serialize(sw, dataClass);
            sw.Close();
            return sw.ToString();
        }
    }

    /// <summary>
    /// XML序列化接口(元素值序列化為單引號格式)
    /// </summary>
    /// <typeparam name="T">泛型類</typeparam>
    /// <param name="dataClass">序列化對象</param>
    /// <returns></returns>
    public static string XMLToSingleQuotationMarkSerialization<T>(T dataClass) where T : class
    {
        using (StringWriter sw = new StringWriter())
        {
            //此處T類必須是Public類型
            Type t = dataClass.GetType();
            XmlSerializer serializer = new XmlSerializer(dataClass.GetType());
            serializer.Serialize(sw, dataClass);
            sw.Close();

            string dataStr = sw.ToString();
            string newDataStr = dataStr.Replace("\"", "'");   //將雙引號轉(zhuǎn)換為單引號,方便部分引擎解析
            return newDataStr;
        }
    }
    //轉(zhuǎn)義字符:(當(dāng)屬性值中含特殊字符時(shí),為避免解析出錯(cuò),需使用轉(zhuǎn)義字符)
    //1、 &lt;      <      小于號 
    //2、 &gt;      >      大于號
    //3、 &amp;     &      和
    //4、 &apos;    '      單引號
    //5、 &quot;    "      雙引號
    //6、 &lt;=     <=     小于等于
    //7、 &gt;=     >=     大于等于


    /// <summary>
    /// XML反序列化接口
    /// </summary>
    /// <typeparam name="T">泛型類</typeparam>
    /// <param name="path">文件路徑</param>
    /// <returns></returns>
    public static T XMLRead<T>(string path) where T : class
    {
        StreamReader sReader = new StreamReader(path);
        string xmlStr = sReader.ReadToEnd();
        try
        {
            using (StringReader sr = new StringReader(xmlStr))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(sr) as T;
            }
        }
        catch (Exception)
        {
            return null;
        }
    }
    #endregion

    #region CSV
    private static char _csvSeparator = ',';
    private static bool _trimColumns = false;

    //解析一行
    private static List<string> ParseLine(string line)
    {
        StringBuilder _columnBuilder = new StringBuilder();
        List<string> Fields = new List<string>();
        bool inColum = false; //是否是在一個(gè)列元素里
        bool inQuotes = false; //是否需要轉(zhuǎn)義
        bool isNotEnd = false; //讀取完畢未結(jié)束轉(zhuǎn)義
        _columnBuilder.Remove(0, _columnBuilder.Length);

        //空行也是一個(gè)空元素,一個(gè)逗號是2個(gè)空元素
        if (line == "")
        {
            Fields.Add("");
        }
        // Iterate through every character in the line  遍歷行中的每個(gè)字符
        for (int i = 0; i < line.Length; i++)
        {
            char character = line[i];

            //If we are not currently inside a column   如果我們現(xiàn)在不在一列中
            if (!inColum)
            {
                // If the current character is a double quote then the column value is contained within
                //如果當(dāng)前字符是雙引號,則列值包含在內(nèi)
                // double quotes, otherwise append the next character
                //雙引號,否則追加下一個(gè)字符
                inColum = true;
                if (character == '"')
                {
                    inQuotes = true;
                    continue;
                }
            }
            // If we are in between double quotes   如果我們處在雙引號之間
            if (inQuotes)
            {
                if ((i + 1) == line.Length) //這個(gè)字符已經(jīng)結(jié)束了整行
                {
                    if (character == '"') //正常轉(zhuǎn)義結(jié)束,且該行已經(jīng)結(jié)束
                    {
                        inQuotes = false;
                        continue;
                    }
                    else //異常結(jié)束,轉(zhuǎn)義未收尾
                    {
                        isNotEnd = true;
                    }
                }
                else if (character == '"' && line[i + 1] == _csvSeparator) //結(jié)束轉(zhuǎn)義,且后面有可能還有數(shù)據(jù)
                {
                    inQuotes = false;
                    inColum = false;
                    i++; //跳過下一個(gè)字符
                }
                else if (character == '"' && line[i + 1] == '"') //雙引號轉(zhuǎn)義
                {
                    i++; //跳過下一個(gè)字符
                }
                else if (character == '"') //雙引號單獨(dú)出現(xiàn)(這種情況實(shí)際上已經(jīng)是格式錯(cuò)誤,為了兼容暫時(shí)不處理)
                {
                    throw new System.Exception("格式錯(cuò)誤,錯(cuò)誤的雙引號轉(zhuǎn)義");
                }
                //其他情況直接跳出,后面正常添加
            }
            else if (character == _csvSeparator)
            {
                inColum = false;
            }
            // If we are no longer in the column clear the builder and add the columns to the list
            ///   結(jié)束該元素時(shí)inColumn置為false,并且不處理當(dāng)前字符,直接進(jìn)行Add
            if (!inColum)
            {
                Fields.Add(_trimColumns ? _columnBuilder.ToString().Trim() : _columnBuilder.ToString());
                _columnBuilder.Remove(0, _columnBuilder.Length);
            }
            else //追加當(dāng)前列
            {
                _columnBuilder.Append(character);
            }
        }

        // If we are still inside a column add a new one (標(biāo)準(zhǔn)格式一行結(jié)尾不需要逗號結(jié)尾,而上面for是遇到逗號才添加的,為了兼容最后還要添加一次)
        if (inColum)
        {
            if (isNotEnd)
            {
                _columnBuilder.Append("\r\n");
            }
            Fields.Add(_trimColumns ? _columnBuilder.ToString().Trim() : _columnBuilder.ToString());
        }
        else //如果inColumn為false,說明已經(jīng)添加,因?yàn)樽詈笠粋€(gè)字符為分隔符,所以后面要加上一個(gè)空元素
        {
            Fields.Add("");
        }
        return Fields;
    }

    /// <summary>
    /// 讀取CSV文件
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public static List<List<string>> CSVRead(string filePath, Encoding encoding)
    {
        List<List<string>> result = new List<List<string>>();
        string content = File.ReadAllText(filePath, encoding); //讀取所有的文本內(nèi)容
        string[] lines = content.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        //以換行回車拆分字符串,去除空格
        //注:回車換行可能對某些文本不適用,這里如果我們出現(xiàn)讀取不正常,可以改用 \n (換行)試試

        for (int i = 0; i < lines.Length; i++)
        {
            List<string> line = ParseLine(lines[i]);
            result.Add(line);
        }
        return result;
    }

    /// <summary>
    /// 生成CSV文件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataList">對象集合</param>
    /// <param name="filePath">文件存儲路徑</param>
    /// <returns></returns>
    public static bool CSVFileSaveData<T>(List<T> dataList, string filePath) where T : class
    {
        bool successFlag = true;

        //所有文本
        StringBuilder sb_Text = new StringBuilder();
        //第一行屬性文本
        StringBuilder strColumn = new StringBuilder();
        //其他行屬性值文本
        StringBuilder strValue = new StringBuilder();
        StreamWriter sw = null;
        var tp = typeof(T);
        //獲取當(dāng)前Type的所有公共屬性                   BindingFlags指定反射查找的范圍
        PropertyInfo[] props = tp.GetProperties(BindingFlags.Public | BindingFlags.Instance);


        try
        {
            //獲取第一行屬性文本
            for (int i = 0; i < props.Length; i++)
            {
                var itemPropery = props[i];
                //檢索自定義特性信息
                AttrForCsvColumnLabel labelAttr = itemPropery.GetCustomAttributes(typeof(AttrForCsvColumnLabel), true).FirstOrDefault() as AttrForCsvColumnLabel;
                if (labelAttr != null)
                {
                    strColumn.Append(labelAttr.Title);
                }
                else
                {
                    strColumn.Append(props[i].Name);
                }
                strColumn.Append(",");
            }
            //移除最后一個(gè)","
            strColumn.Remove(strColumn.Length - 1, 1);
            sb_Text.AppendLine(strColumn.ToString());

            //依次遍歷數(shù)據(jù)列表,得到其他行屬性值文本
            for (int i = 0; i < dataList.Count; i++)
            {
                var model = dataList[i];
                strValue.Clear();
                //獲取每一組數(shù)據(jù)中對應(yīng)的屬性值
                for (int m = 0; m < props.Length; m++)
                {
                    var itemProoery = props[m];
                    var val = itemProoery.GetValue(model, null);
                    if (m == 0)
                    {
                        strValue.Append(val);
                    }
                    else
                    {
                        strValue.Append(",");
                        strValue.Append(val);
                    }
                }
                sb_Text.AppendLine(strValue.ToString());
            }
        }
        catch (System.Exception)
        {
            successFlag = false;
        }
        finally
        {
            if (sw != null)
            {
                sw.Dispose();
            }
        }
        File.WriteAllText(filePath, sb_Text.ToString(), Encoding.Default);
        return successFlag;
    }


    public static void CsvWrite(List<List<string>> datas, string path)
    {
        //所有文本
        StringBuilder sb_Text = new StringBuilder();
        for (int i = 0; i < datas.Count; i++)
        {
            for (int j = 0; j < datas[i].Count; j++)
            {
                sb_Text.Append(datas[i][j] + ",");
            }
            sb_Text.AppendLine();
        }
        File.WriteAllText(path, sb_Text.ToString(), Encoding.Default);
    }

    #endregion

    #region 結(jié)構(gòu)體二進(jìn)制
    /// <summary>
    /// 結(jié)構(gòu)體轉(zhuǎn)換為二進(jìn)制數(shù)組
    /// </summary>
    /// <param name="structObj">結(jié)構(gòu)體</param>
    /// <returns>轉(zhuǎn)換后的二進(jìn)制數(shù)組</returns>
    public static byte[] StructToBytesFunc(object structObj)
    {
        //得到結(jié)構(gòu)體的大小
        int size = Marshal.SizeOf(structObj);

        //創(chuàng)建byte數(shù)組
        byte[] bytes = new byte[size];
        //分配結(jié)構(gòu)體大小的內(nèi)存空間
        IntPtr structPtr = Marshal.AllocHGlobal(size);

        //將結(jié)構(gòu)體拷貝到分配的內(nèi)存空間
        Marshal.StructureToPtr(structObj, structPtr, false);
        //從內(nèi)存空間拷貝到byte數(shù)組
        Marshal.Copy(structPtr, bytes, 0, size);

        //釋放內(nèi)存空間
        Marshal.FreeHGlobal(structPtr);
        //返回byte數(shù)組
        return bytes;
    }


    /// <summary>
    /// byte數(shù)組轉(zhuǎn)結(jié)構(gòu)
    /// </summary>
    /// <param name="bytes">byte數(shù)組</param>
    /// <param name="type">結(jié)構(gòu)類型</param>
    /// <returns>轉(zhuǎn)換后的結(jié)構(gòu)</returns>
    public static object BytesToStructFunc(byte[] bytes, Type type)
    {
        int size = Marshal.SizeOf(type);

        //byte數(shù)組長度小于結(jié)構(gòu)的大小
        if (size > bytes.Length)
        {
            //返回空
            return null;
        }
        //分配結(jié)構(gòu)大小的內(nèi)存空間
        IntPtr structPtr = Marshal.AllocHGlobal(size);

        //將byte數(shù)組拷貝到分配好的內(nèi)存空間
        Marshal.Copy(bytes, 0, structPtr, size);
        //將內(nèi)存空間轉(zhuǎn)換為目標(biāo)結(jié)構(gòu)
        object obj = Marshal.PtrToStructure(structPtr, type);

        //釋放內(nèi)存空間
        Marshal.FreeHGlobal(structPtr);
        //返回結(jié)構(gòu)
        return obj;
    }
    #endregion
}

public class AttrForCsvColumnLabel : Attribute
{
    public string Title { get; set; }
}

到了這里,關(guān)于Unity數(shù)據(jù)解析(Json、XML、CSV、二進(jìn)制)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 在線解析二進(jìn)制報(bào)文

    在線解析二進(jìn)制報(bào)文

    智能設(shè)備應(yīng)用越來越普遍,深入到生活的各個(gè)方面,從智慧農(nóng)業(yè)到智能制造,從水利灌溉到電力傳輸,從工業(yè)生產(chǎn)到智能家居。智能設(shè)備應(yīng)用在各個(gè)領(lǐng)域,設(shè)備之間都是通過數(shù)據(jù)交換來達(dá)到信息共享和互相操作,交換的數(shù)據(jù)都遵守某個(gè)協(xié)議標(biāo)準(zhǔn),在測試時(shí),調(diào)試時(shí)和排查問題

    2024年02月06日
    瀏覽(19)
  • Unity 如何導(dǎo)入二進(jìn)制Spine文件

    Unity 如何導(dǎo)入二進(jìn)制Spine文件

    總是忘記Spine導(dǎo)出二進(jìn)制到Unity的設(shè)置,記錄一下。 TIP 此教程只滿足URP渲染管線與Linear顏色空間的需求 紋理打包器也修改一下拓展名(日常操作) 修改圖集擴(kuò)展名 不要 勾選圖集的 預(yù)乘Alpha ,勾選 溢出 修改圖集擴(kuò)展名 .atlas.txt 可導(dǎo)出以下幾種文件 Default Shader 設(shè)置為 Univer

    2024年02月07日
    瀏覽(27)
  • Python讀取二進(jìn)制文件:深入解析與技術(shù)實(shí)現(xiàn)

    Python讀取二進(jìn)制文件:深入解析與技術(shù)實(shí)現(xiàn)

    目錄 一、引言 二、二進(jìn)制文件的基礎(chǔ) 1、二進(jìn)制文件的組成 2、二進(jìn)制文件的編碼 三、Python讀取二進(jìn)制文件的方法 1、使用內(nèi)置函數(shù)open() 2、使用numpy庫 四、處理讀取的二進(jìn)制數(shù)據(jù) 1、解析數(shù)據(jù) 2. 轉(zhuǎn)換數(shù)據(jù)類型 五、總結(jié)與展望 1、高效讀取二進(jìn)制文件 2、處理復(fù)雜的二進(jìn)制文件

    2024年02月04日
    瀏覽(32)
  • 深入解析位運(yùn)算算法:探索數(shù)字的二進(jìn)制秘密

    位運(yùn)算是計(jì)算機(jī)科學(xué)中的重要概念,用于在二進(jìn)制數(shù)字層面進(jìn)行各種操作。本文將深入介紹位運(yùn)算的基本操作,以及它在判斷、計(jì)算和處理數(shù)字中的應(yīng)用,包括判斷2的冪次方、位圖法、位掩碼和尋找缺失數(shù)字等。 位操作是通過對數(shù)字的二進(jìn)制表示進(jìn)行操作,實(shí)現(xiàn)各種功能。

    2024年02月11日
    瀏覽(21)
  • [unity] 音頻的二進(jìn)制流轉(zhuǎn)化為audioclip的兩種方式

    1、將返回的byte[]數(shù)組,轉(zhuǎn)換成float[]數(shù)組,然后將通過 audioSource.clip.SetData()方法,將音頻數(shù)據(jù)賦給audiosource,實(shí)現(xiàn)語音播放;但這種只有wav很有可以直接用mp3需要第三方庫,我沒有試過 mp3的請參考:https://blog.csdn.net/L877790502/article/details/119042479 2、將返回的btye[]數(shù)組,使用file

    2024年02月11日
    瀏覽(43)
  • 將數(shù)據(jù)轉(zhuǎn)二進(jìn)制流文件,用PostMan發(fā)送二進(jìn)制流請求

    將數(shù)據(jù)轉(zhuǎn)二進(jìn)制流文件,用PostMan發(fā)送二進(jìn)制流請求

    一、將byte數(shù)組轉(zhuǎn)二進(jìn)制流文件,并保存到本地 byte [] oneshotBytes=new byte[]{78,-29,51,-125,86,-105,56,82,-94,-115,-22,-105,0,-45,-48,-114,27,13,38,45,-24,-15,-13,46,88,-90,-66,-29,52,-23,40,-2,116,2,-115,17,36,15,-84,88,-72,22,-86,41,-90,-19,-58,19,99,-4,-63,29,51,-69,117,-120,121,3,-103,-75,44,64,-58,-34,73,-22,110,-90,92,-35,-18,-128,16,-

    2024年02月15日
    瀏覽(30)
  • 【FPGA仿真】Matlab生成二進(jìn)制、十六進(jìn)制的txt數(shù)據(jù)以及Vivado讀取二進(jìn)制、十六進(jìn)制數(shù)據(jù)并將結(jié)果以txt格式保存

    在使用Vivado軟件進(jìn)行Verilog程序仿真時(shí)可能需要對模塊輸入仿真的數(shù)據(jù),因此我們需要一個(gè)產(chǎn)生數(shù)據(jù)的方法(二進(jìn)制或者十六進(jìn)制的數(shù)據(jù)),Matlab軟件是一個(gè)很好的工具,當(dāng)然你也可以使用VS等工具。 以下分別給出了使用Matlab模擬產(chǎn)生二進(jìn)制和十六進(jìn)制數(shù)據(jù)的例子,例子僅供參

    2024年02月01日
    瀏覽(145)
  • 【華為OD機(jī)試真題 C++語言】101、二進(jìn)制差異數(shù) | 機(jī)試真題+思路參考+代碼解析

    ??個(gè)人博客首頁: KJ.JK ? ??專欄介紹: 華為OD機(jī)試真題匯總,定期更新華為OD各個(gè)時(shí)間階段的機(jī)試真題,每日定時(shí)更新,本專欄將使用C++語言進(jìn)行更新解答,包含真題,思路分析,代碼參考,歡迎大家訂閱學(xué)習(xí) ??題目描述 對于任意兩個(gè)正整數(shù)A和B,定義它們之間的差異值和

    2024年02月15日
    瀏覽(24)
  • C語言二進(jìn)制數(shù)據(jù)和16進(jìn)制字符串互轉(zhuǎn)

    知識點(diǎn):結(jié)構(gòu)體中的“伸縮型數(shù)組成員”(C99新增) C99新增了一個(gè)特性:伸縮型數(shù)組成員(flexible array member),利用這項(xiàng)特性聲明的結(jié)構(gòu),其最后一個(gè)數(shù)組成員具有一些特性。第1個(gè)特性是,該數(shù)組不會立即存在。第2個(gè)特性是,使用這個(gè)伸縮型數(shù)組成員可以編寫合適的代碼,就

    2024年02月13日
    瀏覽(28)
  • 使用 WebSocket 發(fā)送二進(jìn)制數(shù)據(jù):最佳實(shí)踐

    使用 WebSocket 發(fā)送二進(jìn)制數(shù)據(jù):最佳實(shí)踐

    WebSocket ?技術(shù)提供了一種在客戶端和服務(wù)器間建立持久連接的方法,使得雙方可以在打開連接后隨時(shí)發(fā)送數(shù)據(jù),而不必?fù)?dān)心建立復(fù)雜的持久連接機(jī)制。同時(shí),使用二進(jìn)制數(shù)據(jù),如ArrayBuffer,可以更有效率地傳送圖像、聲音等信息。本指南旨在深入探討如何使用WebSocket傳輸二進(jìn)

    2024年04月09日
    瀏覽(18)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包