快速学习——7、读取解析JSON(一)利用LitJson,根据对象,生成JSON文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35030499/article/details/82795005

推荐一些网站  JSON在线验证   菜鸟在线之JSON教程  具体语法规则自行查看 ,主要讲解如何读取与解析


JSON 语法规则

  • 数据在名称/值对中
  • 数据由逗号分隔
  • 大括号保存对象
  • 中括号保存数组

示例

{
"LOL": [
{ "name":"德玛西亚" , "prise":"7300" }, 
{ "name":"皇子" , "prise":"6300" }, 
{ "name":"无极剑圣" , "prise":"4800" }
]
}

先看下对象如何转化为json文本的,之前需要导入LitJson

网上解析json 很多 ,只写litjson和unity3d自带的的

下载litjson  dll,导入工程,然后添加dll引用

随便写一些类,加入变量,利用JsonMapper.ToJson();生成JS文本

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

namespace JSON
{
    class Program
    {
        static void Main(string[] args)
        {
            Book b1 = new Book("崛起", 199);
            Book b2 = new Book("提莫队长", 123);
            Student s1 = new Student(001, "小明", false, new Book[] { b1, b2 });
            Student s2 = new Student(002, "小红", true, new Book[] { b1, b1, b2 });

            Student[] sArray = new Student[] { s1, s2 };
            string json = JsonMapper.ToJson(sArray);
            Console.WriteLine(json);

            Console.ReadKey();
        }
    }

    [Serializable]
    public class Student
    {
        public int index;
        public string studentName;
        public bool sex;
        public Book[] books;

        public Student()
        {
        }

        public Student(int index, string studentName, bool sex, Book[] books)
        {
            this.index = index;
            this.studentName = studentName;
            this.sex = sex;
            this.books = books;
        }
    }

    [Serializable]
    public class Book
    {
        public string bookName;
        public int prise;

        public Book()   //有时不写默认构造 会报错
        {
        }

        public Book(string bookName, int prise)
        {
            this.bookName = bookName;
            this.prise = prise;
        }
    }
}

  运行结果

扫描二维码关注公众号,回复: 3401133 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_35030499/article/details/82795005