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

 

推荐一些网站  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;
        }
    }
}

  运行结果

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值