栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Unity学习笔记】Unity使用JsonUtility解析Json(附注意事项)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Unity学习笔记】Unity使用JsonUtility解析Json(附注意事项)

Json实体类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class StudentData
{
    public string StudentName;
    public string StudentGender;
    public string StudentAge;

}

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

namespace Assets.UIframeWork
{
    [System.Serializable]
   public class StudentDataItems
    {
        public StudentData[] infoList;
    }
}
Json
{
  "infoList": [
    {
      "StudentName": "张三",
      "StudentGender": "男",
      "StudentAge": "23"

    },
    {
      "StudentName": "李四",
      "StudentGender": "女",
      "StudentAge": "23"

    },
    {
      "StudentName": "王五",
      "StudentGender": "男",
      "StudentAge": "23"

    }
  ]
}

把Json文件放到名字为Resources的文件夹下

解析方法的代码
  public void ParseJsonToStr()
    {
        TextAsset ta = Resources.Load("uiJson");
        byte[] ReadByte = Encoding.UTF8.GetBytes(ta.text);
        StudentDataItems dataItems = JsonUtility.FromJson(UTF8Encoding.UTF8.GetString(ReadByte));
        foreach(StudentData studentData in dataItems.infoList)
        {
            Debug.Log("学生姓名为"+studentData.StudentName);
        }
        
    }
结果

注意事项

(1)用于接收的JSON实体类需要声明[Serializable] 序列化。
(2)使用Unity自带方法时,实体类如果是属性成员(public bool has_more{get;set;})的话,在序列化的时候会缺失这些成员,导致解析不出来。将属性改为字段即可。
(3)如何解析的对象是数组,自带的不能成功解析,可以人为将其封装为JSON对象。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/292537.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号