当前位置: 首页 > article >正文

Unity Json实体类快速生成保存工具

Unity Json实体类快速生成保存工具

前提:Newtonsoft.Json
拖文件夹那边用的是odin,直接手打存储文件夹地址。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public class JosnEditor : OdinEditorWindow
{
    [TextArea(2, 20), HideLabel, Title("json", TitleAlignment = TitleAlignments.Centered)]
    public string json;
    [MenuItem("Tools/Json工具")]
    private static void Open()
    {
        GetWindow<JosnEditor>().Show();
    }
    [LabelText("生成的实体类名前缀[遵循类名规则]")]
    public string classHead;
    [LabelText("命名空间")]
    public string nameSpace = "";
    [LabelText("region注释")]
    public string regionName = "json数据实体类";

    [TextArea(2, 20), HideLabel, Title("生成的C#实体类", TitleAlignment = TitleAlignments.Centered)]
    public string result;

    [Button("生成")]
    private void Generate()
    {
        var obj = JsonConvert.DeserializeObject<JObject>(json);
        var sb = new StringBuilder();
        sb.AppendLine("using System.Collections;");
        sb.AppendLine("using System.Collections.Generic;");
        sb.AppendLine("using UnityEngine;");
        sb.AppendLine("");
        sb.AppendLine("/*通过JosnEditor.cs 脚本自动生成...*/");
        if (!string.IsNullOrEmpty(nameSpace))
        {
            sb.AppendLine($"namespace {nameSpace} ");
            sb.AppendLine("{");
        }
        sb.AppendLine($"#region {regionName}");
        Parse(obj, sb);
        sb.AppendLine("#endregion");
        if (!string.IsNullOrEmpty(nameSpace))
            sb.AppendLine("}");
        result = sb.ToString();
        GenerateLog = DateTime.Now + " Generate";
    }
    [Button("保存")]
    private void Save()
    {
        if (!Directory.Exists(SavePath))
        {
            Directory.CreateDirectory(SavePath);
        }
        if (!SavePath.EndsWith("/"))
        {
            SavePath = SavePath + "/";
        }
        var newSavePath = SavePath + classHead + "Root.cs";
        if (File.Exists(newSavePath))
        {
            File.Delete(newSavePath);
        }
        File.WriteAllText(newSavePath, result);
        AssetDatabase.Refresh();
    }

    [LabelText("json存储文件夹")]
    [FolderPath]
    public string SavePath = "Assets/Scripts/";
    [ReadOnly]
    public string GenerateLog = "请输入json数据";
    private void Parse(JObject obj, StringBuilder sb, string className = "Root")
    {
        if (obj == null) return;
        List<JObject> objs = new List<JObject>();
        List<string> names = new List<string>();
        sb.AppendLine($"public class {classHead}{className}");
        sb.AppendLine("{");
        foreach (var p in obj.Properties())
        {
            if (p.Value.Type != JTokenType.Array)
            {
                string type = "string";
                switch (p.Value.Type)
                {
                    case JTokenType.Object:
                        var cm = UpperFirst(p.Name);
                        sb.AppendLine($"    public {classHead}{cm} {p.Name};");
                        names.Add(cm);
                        objs.Add(p.Value as JObject);
                        continue;
                    case JTokenType.Integer:
                        if ((long)p.Value > int.MaxValue)
                        {
                            type = "long";
                        }
                        else
                        {
                            type = "int";
                        }
                        break;
                    case JTokenType.Float:
                        type = "float";
                        break;
                    case JTokenType.Boolean:
                        type = "bool";
                        break;
                    case JTokenType.TimeSpan:
                        type = "DateTime";
                        break;
                }
                sb.AppendLine("    /// <summary>");
                sb.AppendLine($"    /// {p.Value}");
                sb.AppendLine("    /// </summary>");
                sb.AppendLine($"    public {type} {p.Name};");
                sb.AppendLine("");
            }
            else
            {
                var arr = p.Value as JArray;
                if (arr.Count > 0)
                {
                    var arrValue = arr[0];
                    switch (arrValue.Type)
                    {
                        case JTokenType.Object:
                            var cmcmm = UpperFirst(p.Name);
                            sb.AppendLine($"    public List<{classHead}{cmcmm}> {p.Name};");
                            names.Add(cmcmm);
                            objs.Add(arrValue as JObject);
                            break;
                        case JTokenType.String:
                            sb.AppendLine($"    public List<string> {p.Name};");
                            break;
                        case JTokenType.Integer:
                            sb.AppendLine($"    public List<int> {p.Name};");
                            break;
                        case JTokenType.Float:
                            sb.AppendLine($"    public List<float> {p.Name};");
                            break;
                        case JTokenType.Boolean:
                            sb.AppendLine($"    public List<bool> {p.Name};");
                            break;

                    }
                }
                else
                {
                    sb.AppendLine($"    public List<string> {p.Name};");
                    Debug.LogError($"json数组:{p.Name}为空");
                }

            }

        }
        sb.AppendLine("}");
        for (int i = 0; i < objs.Count; i++)
        {
            Parse(objs[i], sb, names[i]);
        }
    }
    public static string UpperFirst(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return "";
        }
        var fstr = str.Substring(0, 1);
        fstr = fstr.ToUpper();
        return fstr + str.Substring(1, str.Length - 1);
    }
}




http://www.kler.cn/a/282115.html

相关文章:

  • Unity2D游戏开发-Pak木鱼
  • Module not found: Can‘t resolve ‘tls‘/Module not found: Can‘t resolve ‘net‘
  • (十三)Flink SQL
  • 【自由能系列(中级)】自由能与变分自由能——从状态到配置的效益最大化
  • 手机游玩植物大战僵尸杂交版V2.3.7最新版教程(文章末尾免费直接下载链接)
  • 【Java】—— Java面向对象进阶:Java银行账户管理系统设计与实现
  • 分布式数据一致性小结
  • 【爬虫采集工具】用python开发的快手评论区采集软件
  • 单片机原理及技术(八)—— 串行口的工作原理及应用
  • 墨者学院 手工注入题解(oracle数据库)
  • 华为2016校园招聘上机笔试题
  • 取模+背包
  • 【Word与WPS如何冻结首行首列及窗口】
  • Linux常见基础命令
  • 责任链模式-升级版
  • python办公自动化:使用`Python-PPTX`进行文本框和段落操作
  • Python统计FreeMind测试用例数量
  • 【办公类-54-03】20240828班级点名册模版(双休国定假涂成灰色)
  • 网络层 I(网络层的功能)【★★★★★★】
  • wpf prism 《1》、区域 、模块化