Unity编辑器扩展-Json转c#类

该工具的作用是输入json文本,生成对应的c#解析类型。

在这里插入图片描述
这个功能其实有很多在线json转换网页都能实现,我就是闲的时候想省掉打开网页这一步骤…
而且网页转换了copy过来也要自己改类名,因为网页生成的类名是固定的,这里我也做了自动化处理。

好了上干货

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

public class Yjj_JosnEditor : OdinEditorWindow
{
    [MultiLineProperty(10),HideLabel,Title("json",TitleAlignment = TitleAlignments.Centered)]
    public string json;
    [MenuItem("Yjj/Json工具")]
    private static void Open()
    {
        GetWindow<Yjj_JosnEditor>().Show();
    }
    [LabelText("生成的类型前缀")]
    public string classHead;
    [LabelText("region注释")]
    public string regionName = "json数据类";
    [MultiLineProperty(10), HideLabel, Title("生成结果", TitleAlignment = TitleAlignments.Centered)]
    public string result;
    [Button]
    private void Generate()
    {
        var obj = JsonConvert.DeserializeObject<JObject>(json);
        var sb = new StringBuilder();
        sb.AppendLine("");
        sb.AppendLine($"#region {regionName}");
        Parse(obj, sb);
        sb.AppendLine("#endregion");
        result = sb.ToString();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="sb"></param>
    /// <param name="className"></param>
    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)
            {
                //Debug.Log($"{p.Name}  {p.Value.Type}  {p.Value}");
                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;
                }
                if(p.HasValues && type == "string")
                {
                    sb.AppendLine("    /// <summary>");
                    sb.AppendLine($"    /// {p.Value}");
                    sb.AppendLine("    /// </summary>");
                }
                sb.AppendLine($"    public {type} {p.Name};");
            }
            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.Log($"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 f = str.Substring(0, 1);
        f = f.ToUpper();
        return f + str.Substring(1, str.Length - 1);
    }
}

用到了odin和NewtonJson

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值