unity解析json的两种方式

下面简单说一下unity使用C#脚本如何解析json数据吧。

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

直接给个例子吧

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

{
    "name":"小明",
    "age":20,
    "interests":["sing","run"]
}

2.c#解析类ModelTest.cs

[System.Serializable]
public class ModelTest
{
    public string name;
    public int age;
    public string[] interests;
}

3.测试脚本

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 () {
         
    }
}

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

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

上面同一个json,不再需要写解析类了,解析方式如下:
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);
        }
    }
 
}

 

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解析 JSONUnity 中可以通过 JsonUtility 类来实现。JsonUtility 类是 Unity 提供的一种快速解析和序列化 JSON 数据的方式,它可以将 JSON 数据转换为 C# 对象,并且也可以将 C# 对象序列化为 JSON 数据。 以下是一个简单的示例代码,演示了如何使用 JsonUtility 类来解析 JSON 数据: ```csharp using UnityEngine; using System.Collections; [System.Serializable] public class PlayerData { public string playerName; public int playerLevel; } public class JsonExample : MonoBehaviour { void Start () { string json = "{ \"playerName\": \"Tom\", \"playerLevel\": 5 }"; PlayerData playerData = JsonUtility.FromJson<PlayerData>(json); Debug.Log("Player Name: " + playerData.playerName); Debug.Log("Player Level: " + playerData.playerLevel); } } ``` 在此示例中,我们首先定义了一个名为 PlayerData 的 C# 类,它包含两个公共字段:playerName 和 playerLevel。然后我们创建了一个 JsonExample 类,并在 Start() 方法中定义了一个 JSON 字符串,并使用 FromJson() 方法将其解析为 PlayerData 对象。最后,我们使用 Debug.Log() 方法输出了解析得到的对象的两个字段的值。 需要注意的是,JsonUtility 类只能解析公共字段(public field)或属性(public property),而不能解析私有字段或属性。因此,为了让 JsonUtility 类可以正确解析 JSON 数据,我们需要将要解析的类的字段或属性都定义为公共的。 希望这个简单的示例能够帮助你快速了解如何在 Unity解析 JSON 数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值