C# 将需要的byte []数组转换成json文件字符进行传递与解析使用

本文涉及的产品
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
全局流量管理 GTM,标准版 1个月
云解析 DNS,旗舰版 1个月
简介: 将需要的byte []数组转换成json文件字符进行传递与解析使用LitJson.dll可网上下载using System;using InternalModule;using Json;using UnityEngine;using Li...

将需要的byte []数组转换成json文件字符进行传递与解析使用
LitJson.dll可网上下载

using System;
using InternalModule;
using Json;
using UnityEngine;
using LitJson;

public class TestJson : MonoBehaviour
{

    // 需要存放的数据
    int kill = 10;
    int qte = 14;
    int skill = 41;
    int health = 2;
    int round = 452;
    int score = 857;

    void Awake()
    {
        // 转换成json信息
        JsonData data = new JsonData();
        data["kill"] = kill;
        data["qte"] = qte;
        data["skill"] = skill;
        data["health"] = health;
        data["round"] = round;
        data["score"] = score;

        // 转换成json字符串
        string content = data.ToJson();

        Debug.LogError(content);

        // 将json字符串转换成byte数组
        byte[] details = System.Text.Encoding.UTF8.GetBytes(content);

        // 将byte数组转换成json字符串文件
        string str = System.Text.Encoding.UTF8.GetString(details);

        Debug.LogError(str);

        // 将json字符串文件解析成需要的数据文件
        JsonObject jsonObj = new JsonObject(str);
        int k = int.Parse(jsonObj["kill"].ToString());
        int q = int.Parse(jsonObj["qte"].ToString());
        int s = int.Parse(jsonObj["skill"].ToString());
        int h = int.Parse(jsonObj["health"].ToString());
        int r = int.Parse(jsonObj["round"].ToString());
        int sc = int.Parse(jsonObj["round"].ToString());
    }

}

JsonObject文件,复制内容新建成脚本即可使用

using System;
using System.Collections.Generic;
using System.Text;

namespace Json
{

    /// <summary>
    /// 用于构建属性值的回调
    /// </summary>
    /// <param name="Property"></param>
    public delegate void SetProperties(JsonObject Property);

    /// <summary>
    /// JsonObject属性值类型
    /// </summary>
    public enum JsonPropertyType
    {
        String,
        Object,
        Array,
        Number,
        Bool,
        Null
    }

    /// <summary>
    /// JSON通用对象
    /// </summary>
    public class JsonObject
    {
        private Dictionary<String, JsonProperty> _property;

        public JsonObject()
        {
            this._property = null;
        }

        public JsonObject(String jsonString)
        {
            this.Parse(ref jsonString);
        }

        public JsonObject(SetProperties callback)
        {
            if (callback != null)
            {
                callback(this);
            }
        }

        /// <summary>
        /// Json字符串解析
        /// </summary>
        /// <param name="jsonString"></param>
        private void Parse(ref String jsonString)
        {
            int len = jsonString.Length;
            if (String.IsNullOrEmpty(jsonString) || jsonString.Substring(0, 1) != "{" || jsonString.Substring(jsonString.Length - 1, 1) != "}")
            {
                throw new ArgumentException("传入文本不符合Json格式!" + jsonString);
            }
            Stack<Char> stack = new Stack<char>();
            Stack<Char> stackType = new Stack<char>();
            StringBuilder sb = new StringBuilder();
            Char cur;
            bool convert = false;
            bool isValue = false;
            JsonProperty last = null;
            bool isString = false;
            for (int i = 1; i <= len - 2; i++)
            {
                cur = jsonString[i];
                if (cur == '}')
                {
                    ;
                }
                if (cur == ' ' && !isString)
                {
                    ;
                }
                else if ((cur == '\'' || cur == '\"') && !convert && stack.Count == 0 && !isValue)
                {
                    sb.Length = 0;
                    stack.Push(cur);
                }
                else if ((cur == '\'' || cur == '\"') && !convert && stack.Count > 0 && stack.Peek() == cur && !isValue)
                {
                    stack.Pop();
                }
                else if ( (cur == '[' || cur == '{') && stack.Count == 0)
                {
                    stackType.Push(cur == '[' ? ']' : '}');
                    sb.Append(cur);
                }
                else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Peek() == cur)
                {
                    stackType.Pop();
                    sb.Append(cur);
                }
                else if (cur == ':' && stack.Count == 0 && stackType.Count == 0 && !isValue)
                {
                    last = new JsonProperty();
                    this[sb.ToString()] = last;
                    isValue = true;
                    sb.Length = 0;
                }
                else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
                {
                    if (last != null)
                    {
                        String temp = sb.ToString();
                        last.Parse(ref temp);
                    }
                    isValue = false;
                    sb.Length = 0;
                }
                else
                {
                    if (cur == '"')
                    {
                        isString = !isString;
                    }
                    sb.Append(cur);
                }
            }
            if (sb.Length > 0 && last != null && last.Type == JsonPropertyType.Null)
            {
                String temp = sb.ToString();
                last.Parse(ref temp);
            }
        }

        /// <summary>
        /// 获取属性
        /// </summary>
        /// <param name="PropertyName"></param>
        /// <returns></returns>
        public JsonProperty this[String PropertyName]
        {
            get
            {
                JsonProperty result = null;
                if (this._property != null && this._property.ContainsKey(PropertyName))
                {
                    result = this._property[PropertyName];
                }
                return result;
            }
            set
            {
                if (this._property == null)
                {
                    this._property = new Dictionary<string, JsonProperty>(StringComparer.OrdinalIgnoreCase);
                }
                if (this._property.ContainsKey(PropertyName))
                {
                    this._property[PropertyName] = value;
                }
                else
                {
                    this._property.Add(PropertyName, value);
                }
            }
        }

        /// <summary>
        /// 通过此泛型函数可直接获取指定类型属性的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="PropertyName"></param>
        /// <returns></returns>
        public virtual T Properties<T>(String PropertyName) where T : class
        {
            JsonProperty p = this[PropertyName];
            if (p != null)
            {
                return p.GetValue<T>();
            }
            return default(T);
        }
        
        /// <summary>
        /// 获取属性名称列表
        /// </summary>
        /// <returns></returns>
        public String[] GetPropertyNames()
        {
            if (this._property == null)
                return null;
            String[] keys = null;
            if (this._property.Count > 0)
            {
                keys = new String[this._property.Count];
                this._property.Keys.CopyTo(keys, 0);
            }
            return keys;
        }

        /// <summary>
        /// 移除一个属性
        /// </summary>
        /// <param name="PropertyName"></param>
        /// <returns></returns>
        public JsonProperty RemoveProperty(String PropertyName)
        {
            if (this._property != null && this._property.ContainsKey(PropertyName))
            {
                JsonProperty p = this._property[PropertyName];
                this._property.Remove(PropertyName);
                return p;
            }
            return null;
        }

        /// <summary>
        /// 是否为空对象
        /// </summary>
        /// <returns></returns>
        public bool IsNull()
        {
            return this._property == null;
        }

        public override string ToString()
        {
            return this.ToString("");
        }

        /// <summary>
        /// ToString...
        /// </summary>
        /// <param name="format">格式化字符串</param>
        /// <returns></returns>
        public virtual string ToString(String format)
        {
            if (this.IsNull())
            {
                return "{}";
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (String key in this._property.Keys)
                {
                    sb.Append(",");
                    sb.Append("\"").Append(key).Append("\"").Append(": ");
                    sb.Append(this._property[key].ToString(format));

                }
                if (this._property.Count > 0)
                {
                    sb.Remove(0, 1);
                }
                sb.Insert(0, "{");
                sb.Append("}");
                return sb.ToString();
            }
        }
    }

    /// <summary>
    /// JSON对象属性
    /// </summary>
    public class JsonProperty
    {
        private JsonPropertyType _type;
        private String _value;
        private JsonObject _object;
        private List<JsonProperty> _list;
        private bool _bool;
        private double _number;

        public JsonProperty()
        {
            this._type = JsonPropertyType.Null;
            this._value = null;
            this._object = null;
            this._list = null;
        }

        public JsonProperty(Object value)
        {
            this.SetValue(value);
        }

        /// <summary>
        /// Json字符串解析
        /// </summary>
        /// <param name="jsonString"></param>
        public void Parse(ref String jsonString)
        {
            if (String.IsNullOrEmpty(jsonString))
            {
                if (jsonString == "")
                {
                    this.SetValue("");
                }
                else
                {
                    this.SetValue(null);    
                }
            }
            else
            {
                string first = jsonString.Substring(0, 1);
                string last = jsonString.Substring(jsonString.Length - 1, 1);
                if (first == "[" && last == "]")
                {
                    this.SetValue(this.ParseArray(ref jsonString));
                }
                else if (first == "{" && last=="}")
                {
                    this.SetValue(this.ParseObject(ref jsonString));
                }
                else if ((first == "'" || first == "\"") && first == last)
                {
                   this.SetValue( this.ParseString(ref jsonString));
                }
                else if (jsonString == "true" || jsonString == "false")
                {
                    this.SetValue(jsonString == "true" ? true : false);
                }
                else if (jsonString == "null")
                {
                    this.SetValue(null);
                }
                else
                {
                    double d = 0;
                    if (double.TryParse(jsonString, out d))
                    {
                        this.SetValue(d);
                    }
                    else
                    {
                        this.SetValue(jsonString);
                    }
                }
            }
        }

        /// <summary>
        /// Json Array解析
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        private List<JsonProperty> ParseArray(ref String jsonString)
        {
            List<JsonProperty> list = new List<JsonProperty>();
            int len = jsonString.Length;
            StringBuilder sb = new StringBuilder();
            Stack<Char> stack = new Stack<char>();
            Stack<Char> stackType = new Stack<Char>();
            bool conver = false;
            Char cur;
            for (int i = 1; i <= len - 2; i++)
            {
                cur = jsonString[i];
                if ((cur == '\'' && stack.Count == 0 && !conver && stackType.Count == 0) || (cur == '\"' && stack.Count == 0 && !conver && stackType.Count == 0))
                {
                    sb.Length = 0;
                    sb.Append(cur);
                    stack.Push(cur);
                }
                else if (cur == '\\' && stack.Count > 0 && !conver)
                {
                    sb.Append(cur);
                    conver = true;
                }
                else if (conver == true)
                {
                    conver = false;

                    if (cur == 'u')
                    {
                        sb.Append(new char[] { cur, jsonString[i + 1], jsonString[i + 2], jsonString[i + 3], jsonString[i + 4] });
                        i += 4;
                    }
                    else
                    {
                        sb.Append(cur);
                    }
                }
                else if ((cur == '\'' || cur == '\"') && !conver && stack.Count>0 && stack.Peek() == cur && stackType.Count == 0)
                {
                    sb.Append(cur);
                    JsonProperty jp = new JsonProperty();
                    string sbStr = sb.ToString();
                    jp.Parse(ref sbStr);
                    list.Add(jp);
                    sb.Length = 0;
                    stack.Pop();
                }else if( (cur == '[' || cur == '{' ) && stack.Count==0 )
                {
                    if (stackType.Count == 0)
                    {
                        sb.Length = 0;
                    }
                    sb.Append( cur);
                    stackType.Push((cur == '[' ? ']' : '}'));
                }
                else if ((cur == ']' || cur == '}') && stack.Count == 0 && stackType.Count>0 && stackType.Peek() == cur)
                {
                    sb.Append(cur);
                    stackType.Pop();
                    if (stackType.Count == 0)
                    {
                        JsonProperty jp = new JsonProperty();
                        string sbStr = sb.ToString();
                        jp.Parse(ref sbStr);
                        list.Add(jp);
                        sb.Length = 0;
                    }

                }
                else if (cur == ',' && stack.Count == 0 && stackType.Count == 0)
                {
                    if (sb.Length > 0)
                    {
                        JsonProperty jp = new JsonProperty();
                        string sbStr = sb.ToString();
                        jp.Parse(ref sbStr);
                        list.Add(jp);
                        sb.Length = 0;
                    }
                }
                else
                {
                    sb.Append(cur);
                }      
            }
            if (stack.Count > 0 || stackType.Count > 0)
            {
                list.Clear();
                throw new ArgumentException("无法解析Json Array对象!");
            }
            else if (sb.Length > 0)
            {
                JsonProperty jp = new JsonProperty();
                string sbStr = sb.ToString();
                jp.Parse(ref sbStr);
                list.Add(jp);
            }
            return list;
        }


        /// <summary>
        /// Json String解析
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        private String ParseString(ref String jsonString)
        { 
            int len = jsonString.Length;
            StringBuilder sb = new StringBuilder();
            bool conver = false;
            Char cur;
            for (int i = 1; i <= len - 2; i++)
            {
                cur = jsonString[i];
                if (cur == '\\' && !conver)
                {
                    conver = true;
                }
                else if (conver == true)
                {
                    conver = false;
                    if (cur == '\\' || cur == '\"' || cur == '\'' || cur == '/')
                    {
                        sb.Append(cur);
                    }
                    else
                    {
                        if (cur == 'u')
                        {
                            String temp = new String(new char[] { jsonString[i + 1], jsonString[i + 2], jsonString[i + 3], jsonString[i + 4] });
                            sb.Append((char)Convert.ToInt32(temp, 16));
                            i += 4;
                        }
                        else
                        {
                            switch (cur)
                            {
                                case 'b':
                                    sb.Append('\b');
                                    break;
                                case 'f':
                                    sb.Append('\f');
                                    break;
                                case 'n':
                                    sb.Append('\n');
                                    break;
                                case 'r':
                                    sb.Append('\r');
                                    break;
                                case 't':
                                    sb.Append('\t');
                                    break;
                            }
                        }
                    }
                }
                else
                {
                    sb.Append(cur);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// Json Object解析
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        private JsonObject ParseObject(ref String jsonString)
        {
            return new JsonObject(jsonString);
        }

        /// <summary>
        /// 定义一个索引器,如果属性是非数组的,返回本身
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public JsonProperty this[int index]
        {
            get
            {
                JsonProperty r = null;
                if (this._type == JsonPropertyType.Array)
                {
                    if (this._list != null && (this._list.Count - 1) >= index)
                    {
                        r = this._list[index];
                    }
                }
                else if (index == 0)
                {
                    return this;
                }
                return r;
            }
        }

        /// <summary>
        /// 提供一个字符串索引,简化对Object属性的访问
        /// </summary>
        /// <param name="PropertyName"></param>
        /// <returns></returns>
        public JsonProperty this[String PropertyName]
        {
            get
            {
                if (this._type == JsonPropertyType.Object)
                {
                    return this._object[PropertyName];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                if (this._type == JsonPropertyType.Object)
                {
                    this._object[PropertyName] = value;
                }
                else
                {
                    throw new NotSupportedException("Json属性不是对象类型!");
                }
            }
        }

        /// <summary>
        /// JsonObject值
        /// </summary>
        public JsonObject Object
        {
            get
            {
                if (this._type == JsonPropertyType.Object)
                    return this._object;
                return null;
            }
        }

        /// <summary>
        /// 字符串值
        /// </summary>
        public String Value
        {
            get
            {
                if (this._type == JsonPropertyType.String)
                {
                    return this._value;
                }
                else if (this._type == JsonPropertyType.Number)
                {
                    return this._number.ToString();
                }
                return null;
            }
        }

        /// <summary>
        /// 布尔值
        /// </summary>
        public bool IsTrue
        {
            get
            {
                if (this._type == JsonPropertyType.Bool)
                {
                    return this._bool;
                }
                return false;
            }
        }

        public JsonProperty Add(Object value)
        {
            if (this._type != JsonPropertyType.Null && this._type != JsonPropertyType.Array)
            {
                throw new NotSupportedException("Json属性不是Array类型,无法添加元素!");
            }
            if (this._list == null)
            {
                this._list = new List<JsonProperty>();
            }
            JsonProperty jp = new JsonProperty(value);
            this._list.Add(jp);
            this._type = JsonPropertyType.Array;
            return jp;
        }

        /// <summary>
        /// Array值,如果属性是非数组的,则封装成只有一个元素的数组
        /// </summary>
        public List<JsonProperty> Items
        {
            get
            {
                if (this._type == JsonPropertyType.Array)
                {
                    return this._list;
                }
                else
                {
                    List<JsonProperty> list = new List<JsonProperty>();
                    list.Add(this);
                    return list;
                }
            }
        }

        /// <summary>
        /// 数值
        /// </summary>
        public double Number
        {
            get
            {
                if (this._type == JsonPropertyType.Number)
                {
                    return this._number;
                }
                else
                {
                    return double.NaN;
                }
            }
        }

        public void Clear()
        {
            this._type = JsonPropertyType.Null;
            this._value = String.Empty;
            this._object = null;
            if (this._list != null)
            {
                this._list.Clear();
                this._list = null;
            }
        }

        public Object GetValue()
        {
            if (this._type == JsonPropertyType.String)
            {
                return this._value;
            }
            else if (this._type == JsonPropertyType.Object)
            {
                return this._object;
            }
            else if (this._type == JsonPropertyType.Array)
            {
                return this._list;
            }
            else if (this._type == JsonPropertyType.Bool)
            {
                return this._bool;
            }
            else if (this._type == JsonPropertyType.Number)
            {
                return this._number;
            }
            else
            {
                return null;
            }
        }

        public virtual T GetValue<T>() where T : class
        {
            return (GetValue() as T);
        }

        public virtual void SetValue(Object value)
        {
            if (value is String)
            {
                this._type = JsonPropertyType.String;
                this._value = (String)value;
            }
            else if (value is List<JsonProperty>)
            {
                this._list = ((List<JsonProperty>)value);
                this._type = JsonPropertyType.Array;
            }
            else if (value is JsonObject)
            {
                this._object = (JsonObject)value;
                this._type = JsonPropertyType.Object;
            }
            else if (value is bool)
            {
                this._bool = (bool)value;
                this._type = JsonPropertyType.Bool;
            }
            else if (value == null)
            {
                this._type = JsonPropertyType.Null;
            }
            else
            {
                double d = 0;
                if (double.TryParse(value.ToString(), out d))
                {
                    this._number = d;
                    this._type = JsonPropertyType.Number;
                }
                else
                {
                    throw new ArgumentException("错误的参数类型!");
                }
            }
        }

        public virtual int Count
        {
            get
            {
                int c = 0;
                if (this._type == JsonPropertyType.Array)
                {
                    if (this._list != null)
                    {
                        c = this._list.Count;
                    }
                }
                else
                {
                    c = 1;
                }
                return c;
            }
        }

        public JsonPropertyType Type
        {
            get { return this._type; }
        }

        public override string ToString()
        {
            return this.ToString("");
        }


        public virtual string ToString(String format)
        {
            StringBuilder sb = new StringBuilder();
            if (this._type == JsonPropertyType.String)
            {
                sb.Append("\"").Append(this._value).Append("\"");
                return sb.ToString();
            }
            else if (this._type == JsonPropertyType.Bool)
            {
                return this._bool ? "true" : "false";
            }
            else if (this._type == JsonPropertyType.Number)
            {
                return this._number.ToString();
            }
            else if (this._type == JsonPropertyType.Null)
            {
                return "null";
            }
            else if (this._type == JsonPropertyType.Object)
            {
                return this._object.ToString();
            }
            else
            {
                if (this._list == null || this._list.Count == 0)
                {
                    sb.Append("[]");
                }
                else
                {
                    sb.Append("[");
                    if (this._list.Count > 0)
                    {
                        foreach (JsonProperty p in this._list)
                        {
                            sb.Append(p.ToString());
                            sb.Append(", ");
                        }
                        sb.Length-=2;
                    }
                    sb.Append("]");
                }
                return sb.ToString();
            }
        }
    }
}

相关文章
|
5月前
|
算法 前端开发 数据处理
小白学python-深入解析一位字符判定算法
小白学python-深入解析一位字符判定算法
72 0
|
5月前
|
SQL 存储 JSON
SQL,解析 json
SQL,解析 json
104 8
|
2月前
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
2月前
|
JSON 小程序 UED
微信小程序 app.json 配置文件解析与应用
本文介绍了微信小程序中 `app.json` 配置文件的详细
198 12
|
2月前
|
JSON 缓存 API
解析电商商品详情API接口系列,json数据示例参考
电商商品详情API接口是电商平台的重要组成部分,提供了商品的详细信息,支持用户进行商品浏览和购买决策。通过合理的API设计和优化,可以提升系统性能和用户体验。希望本文的解析和示例能够为开发者提供参考,帮助构建高效、可靠的电商系统。
51 12
|
3月前
|
C#
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
|
3月前
|
JSON JavaScript 前端开发
一次采集JSON解析错误的修复
两段采集来的JSON格式数据存在格式问题,直接使用PHP的`json_decode`会报错。解决思路包括:1) 手动格式化并逐行排查错误;2) 使用PHP-V8JS扩展在JavaScript环境中解析。具体方案一是通过正则表达式和字符串替换修复格式,方案二是利用V8Js引擎执行JS代码并返回JSON字符串,最终实现正确解析。 简介: 两段采集的JSON数据因掺杂JavaScript代码导致PHP解析失败。解决方案包括手动格式化修复和使用PHP-V8JS扩展在JavaScript环境中解析,确保JSON数据能被正确处理。
|
5月前
|
存储 C#
【C#】大批量判断文件是否存在的两种方法效率对比
【C#】大批量判断文件是否存在的两种方法效率对比
86 1
|
5月前
|
JSON JavaScript API
商品详情数据接口解析返回的JSON数据(API接口整套流程)
商品详情数据接口解析返回的JSON数据是API接口使用中的一个重要环节,它涉及从发送请求到接收并处理响应的整个流程。以下是一个完整的API接口使用流程,包括如何解析返回的JSON数据:
|
4月前
|
C# 开发者
C# 一分钟浅谈:Code Contracts 与契约编程
【10月更文挑战第26天】本文介绍了 C# 中的 Code Contracts,这是一个强大的工具,用于通过契约编程增强代码的健壮性和可维护性。文章从基本概念入手,详细讲解了前置条件、后置条件和对象不变量的使用方法,并通过具体代码示例进行了说明。同时,文章还探讨了常见的问题和易错点,如忘记启用静态检查、过度依赖契约和性能影响,并提供了相应的解决建议。希望读者能通过本文更好地理解和应用 Code Contracts。
67 3

推荐镜像

更多