JSON解析的两种方法

一直比较钟情于json,用来做数据交互,堪称完美!下面简单说一下unity使用C#脚本如何解析json数据吧。

一、写解析类,借助于JsonUtility.FromJson

直接给个例子吧

1.json文件testJson.json内容,存储位置/Users/lpp/Downloads/testJson.json

1

2

3

4

5

{

    "name":"小明",

    "age":20,

    "interests":["sing","run"]

}

2.c#解析类ModelTest.cs

1

2

3

4

5

6

7

[System.Serializable]

public class ModelTest

{

    public string name;

    public int age;

    public string[] interests;

}

3.测试脚本

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

using UnityEngine;

using System.IO;

using System.Text;

 

public class JsonTest : MonoBehaviour {

 

    // Use this for initialization

    void Start () {

 

 

        string jsonTest = File.ReadAllText("/Users/lpp/Downloads/testJson.json", Encoding.UTF8);

        ModelTest obj = JsonUtility.FromJson<ModelTest>(jsonTest);

        Debug.Log(obj.name);

        Debug.Log(obj.age);

        foreach (var inter in obj.interests)

        {

            Debug.Log(inter);

        }

    }

     

    // Update is called once per frame

    void Update () {

         

    }

}

4.输出

二、使用Newtonsoft插件,无需解析类

网上下一个Newtonsoft.Json.dll,拖到Assets下某个位置,

上面同一个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

using UnityEngine;

using System.IO;

using System.Text;

using Newtonsoft.Json.Linq;

 

public class JsonTest : MonoBehaviour {

 

    // Use this for initialization

    void Start () {

 

        string json = File.ReadAllText("/Users/lpp/Downloads/testJson.json", Encoding.UTF8);

        JObject obj = JObject.Parse(json);

 

        Debug.Log(obj["name"].ToString());

        Debug.Log(obj["age"].ToString());

 

        JArray ints = (JArray)obj["interests"];

 

        foreach (var inter in ints)

        {

            Debug.Log(inter);

        }

    }

 

}

  输出同样的内容。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值