Unity3d之json解析研究

 
  json是好东西啊!JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式
      JSON简单易用,我要好好研究一下,和大家共享一下.
      想了解更详细的数据可以参考一下百科:http://baike.baidu.com/view/136475.htm
      好了,我们步入正题:unity3d使用json
      我写了4个方法:ReadJson(),ReadJsonFromTXT();WriteJsonAndPrint(),WriteJsonToFile(string,string).
     想使用JSon需要dll动态链接库
还有一些相应的命名空间using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
首先你需要2个字符串,一个为路径,一个文txt文件。
我的写法如下:
    public TextAsset txt;
    public string filePath;
    public string fileName;
// Use this for initialization
void Start () {
        filePath = Application.dataPath + "/TextFile";
        fileName = filePath + "/File.txt"; 
}

1. //读json数据
    void ReadJson()
    {
        //注意json格式。我的只能在一行写入啊,要不就报错,懂的大牛,不吝赐教啊,这是为什么呢?
        string str = "{'name':'taotao','id':10,'items':[{'itemid':1001,'itemname':'dtao'},{'itemid':1002,'itemname':'test_2'}]}";
        //这里是json解析了
        JsonData jd = JsonMapper.ToObject(str);
        Debug.Log("name=" + jd["name"]);
        Debug.Log("id=" + jd["id"]);
        JsonData jdItems = jd["items"];
        //注意这里不能用枚举foreach,否则会报错的,看到网上
        //有的朋友用枚举,但是我测试过,会报错,我也不太清楚。
        //大家注意一下就好了
        for (int i = 0; i < jdItems.Count; i++)
        {
            Debug.Log("itemid=" + jdItems[i]["itemid"]);
            Debug.Log("itemname=" + jdItems[i]["itemname"]);
        }
        Debug.Log("items is or not array,it's " + jdItems.IsArray);
    }
2.  //从TXT文本里都json
    void ReadJsonFromTXT()
    {
        //解析json
        JsonData jd = JsonMapper.ToObject(txt.text);
        Debug.Log("hp:" + jd["hp"]);
        Debug.Log("mp:" + jd["mp"]);
        JsonData weapon = jd["weapon"];
        //打印一下数组
        for (int i = 0; i < weapon.Count; i++)
        {
            Debug.Log("name="+weapon[i]["name"]);
            Debug.Log("color="+weapon[i]["color"]);
            Debug.Log("durability="+weapon[i]["durability"]);
        }
    }
3.   //写json数据并且打印他
    void WriteJsonAndPrint()
    {
        System.Text.StringBuilder strB = new System.Text.StringBuilder();
        JsonWriter jsWrite = new JsonWriter(strB);
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("Name");
        jsWrite.Write("taotao");
        jsWrite.WritePropertyName("Age");
        jsWrite.Write(25);
        jsWrite.WritePropertyName("MM");
        jsWrite.WriteArrayStart();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("xiaomei");
        jsWrite.WritePropertyName("age");
        jsWrite.Write("17");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("xiaoli");
        jsWrite.WritePropertyName("age");
        jsWrite.Write("18");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteArrayEnd();
        jsWrite.WriteObjectEnd();
        Debug.Log(strB);
        JsonData jd = JsonMapper.ToObject(strB.ToString());
        Debug.Log("name=" + jd["Name"]);
        Debug.Log("age=" + jd["Age"]);
        JsonData jdItems = jd["MM"];
        for (int i = 0; i < jdItems.Count; i++)
        {
            Debug.Log("MM name=" + jdItems[i]["name"]);
            Debug.Log("MM age=" + jdItems[i]["age"]);
        }

}
4. //把json数据写到文件里
    void WriteJsonToFile(string path,string fileName)
    {
        System.Text.StringBuilder strB = new System.Text.StringBuilder();
        JsonWriter jsWrite = new JsonWriter(strB);
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("Name");
        jsWrite.Write("taotao");
        jsWrite.WritePropertyName("Age");
        jsWrite.Write(25);
        jsWrite.WritePropertyName("MM");
        jsWrite.WriteArrayStart();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("xiaomei");
        jsWrite.WritePropertyName("age");
        jsWrite.Write("17");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("xiaoli");
        jsWrite.WritePropertyName("age");
        jsWrite.Write("18");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteArrayEnd();
        jsWrite.WriteObjectEnd();
        Debug.Log(strB);
        //创建文件目录
        DirectoryInfo dir = new DirectoryInfo(path);
        if (dir.Exists)
        {
            Debug.Log("This file is already exists");
        }
        else
        {
            Directory.CreateDirectory(path);
            Debug.Log("CreateFile");
#if UNITY_EDITOR
            AssetDatabase.Refresh();
#endif
        }
        //把json数据写到txt里
        StreamWriter sw;
        if (File.Exists(fileName))
        {
            //如果文件存在,那么就向文件继续附加(为了下次写内容不会覆盖上次的内容)
            sw = File.AppendText(fileName);
            Debug.Log("appendText");
        }
        else
        {
            //如果文件不存在则创建文件
            sw = File.CreateText(fileName);
            Debug.Log("createText");
        }
        sw.WriteLine(strB);
        sw.Close();
#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif

}.
为了大家可以更形象理解一下。我用GUI了
  void OnGUI()
    {
        GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        GUILayout.BeginVertical();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("ReadJson"))
        {
            ReadJson();
        }
        if (GUILayout.Button("ReadJsonFromTXT"))
        {
            ReadJsonFromTXT();
        }
        if (GUILayout.Button("WriteJsonAndPrint"))
        {
            WriteJsonAndPrint();
        }
        if (GUILayout.Button("WriteJsonToFile"))
        {
            WriteJsonToFile(filePath,fileName);
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndVertical();
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
    }

 
服务器上JSON的内容
[{"people":[
{"name":"fff","pass":"123456","age":"1", "info":{"sex":"man"}},
{"name":"god","pass":"123456","age":"1","info":{"sex":"woman"}},
{"name":"kwok","pass":"123456","age":"1","info":{"sex":"man"}},
{"name":"tom","pass":"123456","age":"1","info":{"sex":"woman"}}
]}
]
复制代码 LoadControl_c代码: using UnityEngine;
using System.Collections;
using LitJson; public class LoadControl_c:MonoBehaviour
{
private GameObject plane; public string url = "http://127.0.0.1/test2.txt"; // Use this for initialization
void Start()
{
StartCoroutine(LoadTextFromUrl()); //StartCoroutine(DoSomething()); //Book book = new Book("Android dep"); //InvokeRepeating("LaunchProjectile", 1, 5);
} IEnumerator DoSomething()
{
yield return new WaitForSeconds(3);
} IEnumerator LoadTextFromUrl()
{
if (url.Length > 0)
{
WWW www = new WWW(url);
yield return www;
//string data = www.data.ToString().Substring(1);
string data = www.text.ToString().Substring(1); // 下面是关键
print(data); LitJson.JsonData jarr = LitJson.JsonMapper.ToObject(www.text); if(jarr.IsArray)
{ for (int i = 0; i < jarr.Count; i++)
{
Debug.Log(jarr[i]["people"]); JsonData jd = jarr[i]["people"]; for(int j = 0; j < jd.Count; j++)
{
Debug.Log(jd[j]["name"]);
}
}
}
}
} }

Unity3d之json解析研究的更多相关文章

  1. 项目开发笔记-传单下发 名片替换 文件复制上传/html静态内容替换/json解析/html解析

    //////////////////////////// 注意: 此博客是个人工作笔记 非独立demo////////////////////////////////// .............. ...

  2. 十七、springboot配置FastJson为Spring Boot默认JSON解析框架

    前提 springboot默认自带json解析框架,默认使用jackson,如果使用fastjson,可以按照下列方式配置使用 1.引入fastjson依赖库: maven: <dependen ...

  3. Unity3d使用json与javaserver通信

    Unity3d使用json能够借助LitJson 下载LitJson,复制到Unity3d工作文件夹下 于是能够在代码中实现了 以下发送请求到server并解析 System.Collections. ...

  4. golang struct 定义中json``解析说明

    在代码学习过程中,发现struct定义中可以包含`json:"name"`的声明,所以在网上找了一些资料研究了一下 package main import ( "enco ...

  5. Unity的Json解析<一>--读取Json文件

    本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/50373558 作者:car ...

  6. 年年出妖事,一例由JSON解析导致的"薛定谔BUG"排查过程记录

    前言 做开发这么多年,也碰到无数的bug了.不过再复杂的bug,只要仔细去研读代码,加上debug,总能找到原因. 但是最近公司内碰到的这一个bug,这个bug初看很简单,但是非常妖孽,在一段时间内我 ...

  7. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  8. Json解析工具的选择

    前言 前段时间@寒江不钓同学针对国内Top500和Google Play Top200 Android应用做了全面的分析(具体分析报告见文末的参考资料),其中有涉及到对主流应用使用json框架Gson ...

  9. iOS json 解析遇到error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed.

    Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 38 ...

随机推荐

  1. C语言的作用域规则

    作用域规则 程序中名字的作用域,通俗的讲,就是这个名字在程序中的使用范围.在C语言中,作用域的规则相对比较简单,主要分为 全局作用域 和 局部作用域 两种. 一个变量如果定义在函数中,那么这个变量的作 ...

  2. win7系统.LNK类型文件打开方式的修复办法

    1.首先 win+r 2.打开运行程序 3.输入: regedit 4.找到: 计算机\HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\WINDOWS\currentvers ...

  3. String、Stringbuffer、StringBuilder的区别(转载)

    最近学习到StringBuffer,心中有好些疑问,搜索了一些关于String,StringBuffer,StringBuilder的东西,现在整理一下. 关于这三个类在字符串处理中的位置不言而喻,那 ...

  4. 《Android深度探索HAL与驱动开发》第二章阅读心得

    按照书中所讲的步骤,第一步先准备好搭建Android开发环境所需要的工具:JDK6或以上版本:Eclipse3.4或以上版本:ADT:CDT:Android SDK:Android NDK;交叉编译环 ...

  5. 《C标准库》——之<string.h>

    <string.h>里的字符串操作函数是经常要用到的,因此阅读了源码后自己实现了一些: 拷贝函数 void * Mymemcpy(void * sDst, const void * sSr ...

  6. C#中的选择语句

    一.选择语句 if,else if是如果的意思,else是另外的意思,if'后面跟()括号内为判断条件,如果符合条件则进入if语句执行命令.如果不符合则不进入if语句.else后不用加条件,但是必须与 ...

  7. Eclipse 中 Tomcat启动卡100%(preparing launch delegate...)

    我自己遇到这个问题的时候去百度了好几天,没找到我的解决方案,因为我的错误和别人不一样,但提示却和别人一样,在tomcat启动到100%的时候,卡住了,最后显示45秒不够启动,建议我增加时间,所以结果可 ...

  8. java 枚举类型 构造函数及用法

    // 1. 定义枚举类型 public enum Light { // 利用构造函数传参 RED (1), GREEN (3), YELLOW (2); // 定义私有变量 private int n ...

  9. java 运算符使表达式结果类型自动提升

    1.表达式中的自动类型提升: 表达式求值时,Java自动的隐含的将每个byte.short或char操作数提升为int类型,这些类型的包装类型也是可以的. 例如:short s1 = 1; s1 = ...

  10. Linux防火墙简介及iptables的基本使用

    一.防火墙基础知识 iptables/netfilter:网络防火墙,连接追踪(状态检测) netfilter:工作内核中,让规则能够生效的网络框架(framework) iptables:防火墙规则 ...