unity--Json序列化字典

Unity自己的json序列化是不支持字典格式的。无意间发现了一个全新的json .net库,功能很强大,还支持序列化字典推荐给大家。

https://github.com/JamesNK/Newtonsoft.Json/releases

点击下载,zip. 解压后,把bin/net20/Newtonsoft.Json.dll 拖入unity工程。

写下一段简单的序列化 反序列化json的代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using System;

using Newtonsoft.Json;

 

public class Test : MonoBehaviour

{

    void Start()

    {

    Product product = new Product();
    product.Name = "Apple";
    product.Expiry = new DateTime(2008, 12, 28);
    product.Sizes = new string[] { "Small" };
    product.dic ["key"] = "Value";

    string json = JsonConvert.SerializeObject(product); //序列化
    Movie m = JsonConvert.DeserializeObject(json); //反序列化

        Debug.Log (json);    

            //{
            //    "Name":"Apple",
            //    "Expiry":"2008-12-28T00:00:00",
            //    "Sizes":["Small"],
           //    "dic":{"字典key":"字典Value"}
            //}

unity--Json序列化字典_第1张图片

           //apple

        Debug.Log (m.name);

    }

 

    public class Product

    {

        public string name;

        public Dictionary dic=new Dictionary();

    }

 

}

   

 

 

你可能感兴趣的:(Unity,unity,unity,json,unity序列化,unity反序列化)