Unity的Json解析<一>--读取Json文件
本文章由cartzhang编写,转载请注明出处。 所有权利保留。
文章链接:http://blog.csdn.net/cartzhang/article/details/50373558
作者:cartzhang
Unity的Json解析<一>–读取Json文件
因为需要做一个外部文件配置,考虑了XML和Json,而5.3版本对Json做了更新,所以就尝试一下。
版本更新的Json部分介绍哦:[Unity5.3版本更新的Json部分 ]
https://github.com/cartzhang/UnityJsonTest/blob/master/Assets/JSONSerialization.html
https://unity3d.com/cn/unity/whats-new/unity-5.3
https://blogs.unity3d.com/cn/2015/12/08/unity-5-3-all-new-features-and-more-platforms/
Json的在线编辑
Json parser :http://json.parser.online.fr/
Json在线编辑:http://www.kjson.com/jsoneditor/?f=1
第二个是可以直接下载保存到本地的,此操作甚好啊!
JsonUtility
先看看,在Unity中,我们在其Json工具类中,可用的函数,总共就5个,好少啊!不过,simple is better.
#region 程序集 UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// H:\Unity\Project\JsonReadTest\Library\UnityAssemblies\UnityEngine.dll
#endregion
using System;
namespace UnityEngine
{
//
// 摘要:
// ///
// Utility functions for working with JSON data.
// ///
public static class JsonUtility
{
//
// 摘要:
// ///
// Create an object from its JSON representation.
// ///
//
// 参数:
// json:
// The JSON representation of the object.
//
// type:
// The type of object represented by the JSON.
//
// 返回结果:
// ///
// An instance of the object.
// ///
[WrapperlessIcall]
public static object FromJson(string json, Type type);
public static T FromJson<T>(string json);
//
// 摘要:
// ///
// Overwrite data in an object by reading from its JSON representation.
// ///
//
// 参数:
// json:
// The JSON representation of the object.
//
// objectToOverwrite:
// The object that should be overwritten.
[WrapperlessIcall]
public static void FromJsonOverwrite(string json, object objectToOverwrite);
//
// 摘要:
// ///
// Generate a JSON representation of the public fields of an object.
// ///
//
// 参数:
// obj:
// The object to convert to JSON form.
//
// prettyPrint:
// If true, format the output for readability. If false, format the output for minimum
// size. Default is false.
//
// 返回结果:
// ///
// The object's data in JSON format.
// ///
public static string ToJson(object obj);
//
// 摘要:
// ///
// Generate a JSON representation of the public fields of an object.
// ///
//
// 参数:
// obj:
// The object to convert to JSON form.
//
// prettyPrint:
// If true, format the output for readability. If false, format the output for minimum
// size. Default is false.
//
// 返回结果:
// ///
// The object's data in JSON format.
// ///
[WrapperlessIcall]
public static string ToJson(object obj, bool prettyPrint);
}
}
可以看到,主要就是创建对象的和变成Json格式的两个类型。
准备工作
我们需要一个Json文件,这是主角啊,就是要读取其内容啊。
好了。我随便写了个,命名为Test.json放到了我的.\Assets\Resources\目录下;
Json文件内容如下:
{"gameName":"JSON Serializer Test","version":"1.0","isStereo":"false","isUseHardWare":"true","statusList":[{"name":"test","id":"1u702"}]}
创建对象类
首先,我们需要创建一个对象类,用来存放从Json文本中读取的内容。
给这个类命名为GameStatus.cs
using UnityEngine;
using System;
using System.Collections;
[Serializable]
public class GameStatus
{
public string gameName;
public string version;
public bool isStereo;
public bool isUseHardWare;
public refencenes[] statusList;
}
[Serializable]
public class refencenes
{
public string name;
public int id;
}
需要一个读取类
这个写了一个静态类,以后也可添加写的内容
名字为LoadJson.cs
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class LoadJson : MonoBehaviour
{
public static GameStatus LoadJsonFromFile()
{
BinaryFormatter bf = new BinaryFormatter();
if (!File.Exists(Application.dataPath + "/Resources/Test.json"))
{
return null;
}
StreamReader sr = new StreamReader(Application.dataPath + "/Resources/Test.json");
//FileStream file = File.Open(Application.dataPath + "/Test.json", FileMode.Open, FileAccess.ReadWrite);
//if (file.Length == 0)
//{
// return null;
//}
//string json = (string)bf.Deserialize(file);
//file.Close();
if (sr == null)
{
return null;
}
string json = sr.ReadToEnd();
if (json.Length > 0)
{
return JsonUtility.FromJson<GameStatus>(json);
}
return null;
}
}
说明:代码被注释掉的部分,是从网上找的,解析Json为二进制格式,然后在反序列化为字符串,结果,可能是编码格式问题,不能正确的反序列化,总是报错。
我表示无奈,只好从写实使用了StreamReader来处理。
调用
调用蛮简单的,就是在Update中,使用L键来加载Json文件。
代码如下:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class ReadJson : MonoBehaviour
{
void Update()
{
if(Input.GetKeyDown(KeyCode.S))
{
//Save();
}
if (Input.GetKeyDown(KeyCode.L))
{
GameStatus status = LoadJson.LoadJsonFromFile();
Debug.Log(status);
}
}
}
测试结果
在场景中,建立一个空对象,然后把ReadJson拖拽到对象上,运行,按下L键,就可以使用断点查看,当然也后Log输出。
结果如下图:
说明
总体过程都很简单。工程就不一一上传。
若有问题,请随时联系!
非常感谢!
Unity的Json解析<一>--读取Json文件的更多相关文章
- Unity的Json解析<二>–写Json文件
本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/50378805 作者:car ...
- 深入学习python解析并读取PDF文件内容的方法
这篇文章主要学习了python解析并读取PDF文件内容的方法,包括对学习库的应用,python2.7和python3.6中python解析PDF文件内容库的更新,包括对pdfminer库的详细解释和应 ...
- python json及mysql——读取json文件存sql、数据库日期类型转换、终端操纵mysql及python codecs读取大文件问题
preface: 近期帮师兄处理json文件,须要读到数据库里面,以备其兴许从数据库读取数据.数据是关于yelp站点里面的: https://github.com/Yelp/dataset-examp ...
- springMVC实现REST开发详解(补充Json解析问题以及静态文件404错误解决办法)
一.什么是REST? 符合REST约束风格和原则的应用程序或者设计就是REST 例如: /blog/1 HTTP GET =>查询id=1的blog /blog/1 HTTP DE ...
- 简单使用JSON,JavaScript读取JSON文本(三)
JavaScript 读取 JSON 文本转换为对象 JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 Jav ...
- localStorage 如何存储JSON数据并读取JSON数据
localStorage是HTML5提供的再客户端实现本地存储的一种方法,但是localStorage方法只能存储字符串数据,有时候我们需要存储对象到本地比如:JSON:那么,localStorage ...
- JSON解析工具-org.json使用教程
转自:http://www.open-open.com/lib/view/open1381566882614.html 一.简介 org.json是Java常用的Json解析工具,主要提供JSONO ...
- Java:JSON解析工具-org.json
一.简介 org.json是Java常用的Json解析工具,主要提供JSONObject和JSONArray类,现在就各个类的使用解释如下. 二.准备 1.在使用org.json之前,我们应该先从该网 ...
- Newtonsoft.Json 通过 JObject 读取 json对像 超简单
/* json 格式的字符串解析 格式化 { "input": { "size": 193156, "type": "image/ ...
随机推荐
- 关于NumPy的坑
初次接触NumPy的时候,感叹这个功能的强大,实现了Python对矩阵的运算,但在写一个项目的时候,发现了一个巨坑无比的情况 分隔符================= 对于被 ...
- BindingResult不能获取错误对象
BindingResult不能获取错误对象,代码如下: @RequestMapping(value = "/login") public String error4( Model ...
- [SharePoint][SharePoint Designer 入门经典]Chapter8 XSLT数据试图和表单
本章概要: 1.不是利用XSLT web部件 2.使用XSLT web部件创建数据试图 3.使用XSLT表单web部件创建自定义表单 4.利用自定义动作执行列表表单
- muduo库源码剖析(二) 服务端
一. TcpServer类: 管理所有的TCP客户连接,TcpServer供用户直接使用,生命期由用户直接控制.用户只需设置好相应的回调函数(如消息处理messageCallback)然后TcpSer ...
- git-osc自己定义控件之:CircleImageView
git-osc自己定义控件之:CircleImageView 一.CircleImageView的使用 在项目中能够发现,用户的头像都是圆形的.感觉非常好奇,昨天最终发现了,原来是自定了一个Image ...
- 鸟书shell 学习笔记(二) shell中正則表達式相关
通配符与正則表達式的差别 通配符是bash原生支持的语法,正則表達式是处理字符串的一种表示方式, 正則表達式须要支持的工具支持才干够 语系设置 : export LANG=C grep alias 设 ...
- HDOJ 4944 FSF’s game
http://blog.csdn.net/keshuai19940722/article/details/38519681 不明真相的补一发... FSF's game Time Limit: 900 ...
- ListView的adapter中getView方法一直调用
当ListView的高度不定(比如重写ListView搞成可自己主动的扩展的ListView)或 ListView嵌套在SrollView(高度不定)中,listView中的一个item元素改变会使得 ...
- ios假设写一个提示带动画的View,能够来引导用户行为
先上图: 这个UIView能够这样写: -(id)initWithFrame:(CGRect)frame backImage:(UIImage*)image msgStr:(NSString*)txt ...
- jQuery插件 -- Cookie插件
Cookie是站点设计者放置在client的小文本文件.Cookie能为用户提供非常多的使得,比如购物站点存储用户以前浏览过的产品列表.或者门户站点记住用户喜欢选择浏览哪类新闻. 在用户同意的情况下. ...