Unity中Json 解析(序列化和反序列化)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SolJSONExample
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Company
    {
        public Person CEO { get; set; }
        public List<Person> Staffs { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            {
                string person_info_str = "{\"Name\":\"admin1\", \"Age\": 13}";
                Person person_info = SolJSON.Convert.JsonConverter.ToObject<Person>(person_info_str);

                Console.WriteLine("Name = " + person_info.Name);
                Console.WriteLine("Age = " + person_info.Age);
            }
            {
                string person_infos_str = "[{\"Name\":\"admin1\", \"Age\": 13},{\"Name\":\"admin2\", \"Age\": 20}]";
                List<Person> person_infos = SolJSON.Convert.JsonConverter.ToObject<List<Person>>(person_infos_str);

                foreach (var person_info in person_infos)
                {
                    Console.WriteLine("Name = " + person_info.Name);
                    Console.WriteLine("Age = " + person_info.Age);
                }
            }
            {
                string company_str = "{\"CEO\":{\"Name\":\"admin1\", \"Age\": 13}, \"Staffs\": [{\"Name\":\"admin2\", \"Age\": 25}, {\"Name\":\"admin3\", \"Age\": 20}]}";
                Company company = SolJSON.Convert.JsonConverter.ToObject<Company>(company_str);

                Console.WriteLine("CEO.Name = " + company.CEO.Name);
                Console.WriteLine("Staffs");

                foreach (var staff in company.Staffs)
                {
                    Console.WriteLine("Name = " + staff.Name);
                    Console.WriteLine("Age = " + staff.Age);
                }
            }
        }
    }
}


字符串转化为json数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SolJSONExample
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person()
            {
                Name = "admin1",
                Age = 16
            };

            Console.WriteLine("json string = " + SolJSON.Convert.JsonConverter.ToJSON(person));
        }
    }
}


取出Json数据中的某一个元素
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SolJSONExample
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            {
                string person_info_str = "{\"Name\":\"admin1\", \"Age\": 13}";
                SolJSON.Types.JsonObject person_info_json_object = SolJSON.Convert.JsonConverter.ToJsonObject(person_info_str);

                if ( person_info_json_object.Type == SolJSON.Types.JsonObject.TYPE.DICTONARY )
                {
                    if ( person_info_json_object.AsDictonary.Contains("Name") )
                    {
                        Console.WriteLine("Name = " + person_info_json_object.AsDictonary["Name"].AsString);
                    }
                }
            }
            {
                string person_infos_str = "[{\"Name\":\"admin1\", \"Age\": 13},{\"Name\":\"admin2\", \"Age\": 20}]";
                SolJSON.Types.JsonObject person_infos_json_object = SolJSON.Convert.JsonConverter.ToJsonObject(person_infos_str);

                foreach (var person_info in person_infos_json_object.AsArray)
                {
                    Console.WriteLine("Name = " + person_info.AsDictonary["Name"].AsString);
                    Console.WriteLine("Age = " + person_info.AsDictonary["Age"].AsNumber.IntValue);
                }
            }
        }
    }
}


Json字典
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SolJSONExample
{

    class Program
    {
        static void Main(string[] args)
        {
            SolJSON.Types.JsonDictonary person_dict = new SolJSON.Types.JsonDictonary();
            person_dict.Add("Name", new SolJSON.Types.JsonString("admin1"));
            person_dict.Add("Age", new SolJSON.Types.JsonNumber(13));

            Console.WriteLine("json string = " + person_dict.ToString());
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity ,我们可以使用 JsonUtility 类来实现对象的序列序列。对于 Dictionary 类型的对象,我们可以通过将其转换为一个包含键值对的 List 类型对象,然后对 List 类型对象进行序列序列。 下面是一个示例代码: ```csharp using System.Collections.Generic; using UnityEngine; [System.Serializable] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver { [SerializeField] private List<TKey> keys = new List<TKey>(); [SerializeField] private List<TValue> values = new List<TValue>(); // save the dictionary to lists public void OnBeforeSerialize() { keys.Clear(); values.Clear(); foreach (KeyValuePair<TKey, TValue> pair in this) { keys.Add(pair.Key); values.Add(pair.Value); } } // load dictionary from lists public void OnAfterDeserialize() { this.Clear(); for (int i = 0; i < keys.Count; i++) { this.Add(keys[i], values[i]); } } } [System.Serializable] public class MyData { public SerializableDictionary<string, int> myDict = new SerializableDictionary<string, int>(); } public static class JsonHelper { public static string ToJson<T>(T obj) { return JsonUtility.ToJson(obj); } public static T FromJson<T>(string json) { return JsonUtility.FromJson<T>(json); } } public class Example : MonoBehaviour { private MyData data = new MyData(); private void Start() { data.myDict.Add("key1", 1); data.myDict.Add("key2", 2); string json = JsonHelper.ToJson(data); Debug.Log(json); MyData loadedData = JsonHelper.FromJson<MyData>(json); Debug.Log(loadedData.myDict["key1"]); Debug.Log(loadedData.myDict["key2"]); } } ``` 在上面的示例代码,我们定义了一个 SerializableDictionary 类来实现 Dictionary 的序列序列。在 MyData 类使用了 SerializableDictionary 类型的成员变量 myDict。在 JsonHelper 类,我们定义了 ToJson 和 FromJson 方法来将对象转换为 Json 字符串和从 Json 字符串加载对象。在 Example 类,我们创建了一个 MyData 对象,并向其添加了两个键值对。我们将 MyData 对象转换为 Json 字符串并输出到控制台,然后从 Json 字符串加载了一个新的对象,并输出了其的两个值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值