• Unity 数据Json格式的转换


    把对象转换为字节序列的过程称为对象的序列化。

    把字节序列化恢复为对象过程称为对象的反序列化。


    JSON格式的转换,是一大神给我说的,让我拿来存储数据库时对一些数据的处理,感觉特别好用。但是我并没有深入的去学习,这里只是最简单的应用,以下就是一个简单的示例程序。

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using Newtonsoft.Json;  //需要下载Newtonsoft.Json.dll文件,放在Plugins文件夹下
    using System.IO;
    
    public class json : MonoBehaviour {
    
    	// Use this for initialization
    	void Start () {
            writeTxt();//调用写入文本函数
            StartCoroutine(testJson());//调用读取函数
    	}
    	
        void writeTxt()
        {
            MapPosList maplist = new MapPosList();
            maplist.points = new List<GetPointXY>();
            maplist.points.Add(new GetPointXY(100, 78));
            maplist.points.Add(new GetPointXY(54, 121));
            maplist.points.Add(new GetPointXY(56, 845));
            maplist.points.Add(new GetPointXY(221, 56));
            maplist.points.Add(new GetPointXY(454, 23));
            maplist.points.Add(new GetPointXY(10, 12));
            maplist.points.Add(new GetPointXY(45, 65));
            maplist.points.Add(new GetPointXY(898, 887));
            //用json将一个对象转成一个字符串
            string str = JsonConvert.SerializeObject(maplist);
    
            //下面将这个字符串写入本地文本
            StreamWriter sw;
            FileInfo t = new FileInfo("Assets/Streaming Assets/test.txt");
            if (!t.Exists)
            {
                sw = t.CreateText();
            }
            else
            {
                sw = t.AppendText();
            }
            sw.Write(str);
            sw.Close();
            sw.Dispose();
        }
        IEnumerator testJson()
        {
            WWW w = new WWW("file:///D:/Test/Assets/Streaming Assets/test.txt");
            yield return w;
    
            string str = w.text.Trim();
            //通过json将字符串转换成一个对象
            MapPosList data = JsonConvert.DeserializeObject<MapPosList>(str);
            Debug.Log(data.points[0].xPosition);
            yield return null;
        }
        
    }
    public class GetPointXY
    {
        public float xPosition;
        public float yposition;
        public GetPointXY(float x, float y)
        {
            this.xPosition = x;
            this.yposition = y;
        }
    }
    public class MapPosList
    {
        public List<GetPointXY> points;
    }
    


    这里最重要的就是JSON的两个函数:

    JsonConvert.SerializeObject//将对象转换为字符串

    JsonConvert.DeserializeObject//将字符串恢复为一个对象


    这里备份一个Newtonsoft.Json.dll的下载链接,好像各版本都有:

    http://yunpan.cn/cK5Ih7aMmy4ZH  访问密码 b6a4



  • 相关阅读:
    kafka----简单的脚本命令重点
    kafka简单学习----遇到的问题
    nc简单使用
    kafka-sparkstreaming---学习1
    sparkStream---1
    装系统
    spark入门备忘---1
    linux---学习3
    MySql-5.7.17-20解压缩版安装配置
    springboot动态定时任务
  • 原文地址:https://www.cnblogs.com/liang123/p/6325920.html
Copyright © 2020-2023  润新知