Unity 使用LitJson(及一些坑)

LitJson我觉得除了第一次加载dll的速度比NewtonsoftJson快之外,还有Web可以使用估计就没什么比NewtonsoftJson好用了
LitJson官网 可以查阅使用API 比一些博客上面的强多了 也比较简洁
https://litjson.net/

https://github.com/LitJSON/litjson/releases

image.png

这是个官方示例包,如果你的.Net库没有可以去上面下载
把这个文件夹拖出来 放到工程里,这个比引用dll好处是在于可以自己修改自定义序列化,好像都不支持struct优化,突然发现还是我原来自己写的XML读写好用,可以自己随便添加自定义存储类型
image.png

LitJson在序列化一个类中有很多数据,如果存在Dictionary时会报一些迷之BUG,导致序列化失败
就类似于这样

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;

public class Dic
{
    public Dictionary dic;
    public Dic()
    {
        dic = new Dictionary();
    }

}

public class Player
{
    public int id;
    public string name;
    public int hp;
    public Dic dic;
}

public class LitJsonText : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        Player p = new Player
        {
            id = 1,
            name = "zzz",
            hp = 1,
            dic = new Dic
            {
                dic = new Dictionary {
                    { 0, true },
                    { 1, false },
                    { 2, true },
                }
            }
        };



        string json = JsonMapper.ToJson(p);
        File.WriteAllText(Application.dataPath + "/text.json", json);
    }
}

image.png

然后报了个转换类型失败


image.png

但是数据是有的


image.png

然后Key改为string
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;

public class Dic
{
    public Dictionary dic;
    public Dic()
    {
        dic = new Dictionary();
    }

}

public class Player
{
    public int id;
    public string name;
    public int hp;
    public Dic dic;
}

public class LitJsonText : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        Player p = new Player
        {
            id = 1,
            name = "zzz",
            hp = 1,
            dic = new Dic
            {
                dic = new Dictionary {
                    { "0", true },
                    { "1", false },
                    { "2", true },
                }
            }
        };



        string json = JsonMapper.ToJson(p);
        string path = Application.dataPath + "/text.json";
        File.WriteAllText(path, json);
        //取法1
        Player p1 = JsonMapper.ToObject(File.ReadAllText(path));
        //取法2
        JsonData jsonData = JsonMapper.ToObject(File.ReadAllText(path));
        print(jsonData["name"]);
    }
}

然后写入了


image.png

也就是说字典Key必须为string 不然无法写入
LitJson也没办法XML Json 互转
把JsonMapper的脚本改成软转试试


image.png

还是错误
试试这个
image.png

成功了还报错了 但是都是字符串


image.png

image.png

这个是取单个值的print打印
image.png

你可能感兴趣的:(Unity 使用LitJson(及一些坑))