单个实体类,list实体类和实体类字典与json串的互转

参考链接:https://blog.csdn.net/simoral/article/details/80625654 和https://bbs.csdn.net/topics/392289236

以下示例在vs中,创建控制台窗口应用程序,粘贴代码即可看到效果

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

namespace ConsoleApplication1
{
    public class Person
    {
        public string name;
        public string age;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.name = "yxx"; p.age = "12";
            string strJson = JsonConvert.SerializeObject(p);
            //1.单个实体类转json                         
            Console.WriteLine("1:" + strJson);//Print:1:{"name":"yxx","age":"12"} 
            
            Person p1 = new Person();
            p1.name = "abc"; p1.age = "8";

            List lp = new List();
            lp.Add(p);
            lp.Add(p1);
            string listPersonTonStr = JsonConvert.SerializeObject(lp);
            //2.实体类list转json                         
            Console.WriteLine("2:" + listPersonTonStr);//2:[{"name":"yxx","age":"12"},{"name":"abc","age":"8"}]
            //3.json转实体类list
            List listP = JsonConvert.DeserializeObject>(listPersonTonStr);
            Console.WriteLine("3:"+listP.Count+"    "+listP[1].name + "    " + listP[0].age);//3:2    abc    12


            //4.多个实体类用字典转json             
            Dictionary dsp = new Dictionary();
            dsp.Add("one", p);
            dsp.Add("two", p1);
            strJson = JsonConvert.SerializeObject(dsp);
            Console.WriteLine("4:" + strJson);  //Print: 2:{ "one":{ "name":"yxx","age":"12"},"two":{ "name":"yxx","age":"12"} }

            //4.json转多个实体类用字典
            Dictionary temp = JsonConvert.DeserializeObject>(strJson);
            foreach (KeyValuePair item in temp)
            {   //Print:
                //one_yxx__12
                //two_yxx__12
                Console.WriteLine(item.Key + "_" + item.Value.name + "__" + item.Value.age);
            }
            Console.ReadKey();
        }
    }
}

关键记得添加引用

添加引用:using Newtonsoft.Json;

关键代码: JsonConvert.SerializeObject(obj)

其中obj是实体类对象

程序集
程序集下载请点击:程序集下载地址Newtonsoft.Json.dll ,如果您没有资源分,请百度这个Newtonsoft.Json就行

 

你可能感兴趣的:(Unity逻辑运算)