Unity | 使用JsonUtility解析Json

23 篇文章 0 订阅

一、使用注意事项:

  1. 被转换的对象必须是可被序列化的,需要标记 [System.Serializable] 属性;
  2. JsonUtility.FromJson 方法只能接受 json 对象,如果是 json 数组会提示错误: JSON must represent an object type。

二、要解析的Json数据:

{
	"stat": 1,
	"status": 1,
	"msg": "\u64cd\u4f5c\u6210\u529f",
	"data": {
		"ARM": 1,
		"model": [{
			"mname": "1x1",
			"name": "road",
			"pos": { 
				"x": -155,
				"y": 140,
				"direction": 90
			},
			"size": [40, 40] 
		}, {
			"mname": "3x3",
			"name": "park",
			"pos": {
				"x": -35,
				"y": 60,
				"direction": 90
			},
			"size": [119, 119]
		}, {
			"mname": "游乐园",
			"name": "游乐园",
			"pos": {
				"x": 240,
				"y": 180,
				"direction": 90
			},
			"size": [111, 111]
		}]
	}
}

三、解析方法(类中需是字段,不能是属性):

    [Serializable]
    public class Pos
    {
        public int x;
        public int y;
        public int direction;
    }
    [Serializable]
    public class Model
    {
        public string mname;
        public string name;
        public Pos pos;
        public List<int> size;
    }
    [Serializable]
    public class Data
    {
        public int ARM;
        public List<Model> model;
    }
    [Serializable]
    public class JsonObject
    {
        public int stat;
        public int status;
        public string msg;
        public Data data;
    }
    private JsonObject jsonObject;
    private void RecvGetMsg(string json)//通过Json初始化obj的值
    {
        //jsonObject = JsonUtility.FromJson<JsonObject>(json);//方法一
        JsonUtility.FromJsonOverwrite(json, jsonObject);//方法二
        Debug.Log(json+jsonObject.stat + "," + jsonObject.status+"," +jsonObject.data.ARM);
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烫青菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值