Json对象转换模块(自编代码JsonObject.cs)
namespace 信息采集系统.Common
{
/// <summary>
/// Json类型对象,用于其它Json对象继承
/// </summary>
/// <typeparam name="T">自定义类型</typeparam>
[DataContract]
public abstract class JsonObject<T>
{
/// <summary>
/// 将Json对象转换为字节数组
/// </summary>
/// <returns></returns>
public byte[] ToArray()
{
var serializer = new DataContractJsonSerializer(this.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, this);
var b = ms.ToArray();
return b;
}
}
/// <summary>
/// 将Json对象转换为字符串
/// </summary>
/// <returns></returns>
public override string ToString()
{
var b = this.ToArray();
var s = Encoding.UTF8.GetString(b);
return s;
}
/// <summary>
/// 将Json对象转换为字符串,并进行格式化输出
/// </summary>
/// <returns>利于阅读的Json字符串</returns>
public string ToFriendlyString()
{
return this.toFriendlyString(this, 0);
}
private string toFriendlyString(object obj, int level)
{
var sbAll = new StringBuilder();
var type = obj.GetType();
var interfaces = type.GetInterfaces();
if (interfaces.Contains(typeof(System.Collections.IList)))
{
var arr = obj as System.Collections.IList;
var sbLine = new StringBuilder();
sbLine.Append($"\r\n{makeMultiSymbol(level)}[\r\n");
sbAll.Append(sbLine.ToString());
for (int i = 0; i < arr.Count; i++)
{
var item = arr[i];
string line = this.toFriendlyString(item, level + 1);
sbAll.Append(line); if (i < arr.Count - 1)
sbAll.Append(",\r\n");
else
sbAll.Append("\r\n");
}
sbLine = new StringBuilder();
sbLine.Append($"{makeMultiSymbol(level)}]");
sbAll.Append(sbLine.ToString());
}
else
{
var sbLine = new StringBuilder();
sbLine.Append($"{makeMultiSymbol(level)}{{\r\n");
sbAll.Append(sbLine.ToString());
var dict = new Dictionary<int, string[]>();
var fields = type.GetFields(); for (int i = 0; i < fields.Length; i++)
{
var field = fields[i];
var atts = field.GetCustomAttributes(true);
var att = atts.FirstOrDefault(x => x is DataMemberAttribute);
if (att == null) continue;
var order = (att as DataMemberAttribute).Order;
var name = field.Name;
var value = field.GetValue(obj);
sbLine = new StringBuilder();
string strValue;
if (value == null)
strValue = "null";
else
{
var attrType = value.GetType();
if (attrType.IsEnum)
strValue = ((int)value).ToString();
else if (attrType == typeof(string))
strValue = StringExt.ToCodeFormat(value as string);
else if (attrType.IsValueType)
strValue = value.ToString();
else
strValue = this.toFriendlyString(value, level + 1);
}
if (dict.Values.Count(x => x[0] == name) == 0)
{
if (order == -1) order = GetNextOrderID(dict);
dict.Add(order, new string[] { name, strValue });
}
} var properties = type.GetProperties();
for (int i = 0; i < properties.Length; i++)
{
var property = properties[i];
var atts = property.GetCustomAttributes(true);
var att = atts.FirstOrDefault(x => x is DataMemberAttribute);
if (att == null) continue; var order = (att as DataMemberAttribute).Order;
var name = property.Name;
var value = property.GetValue(obj, null);
sbLine = new StringBuilder();
string strValue;
if (value == null)
strValue = "null";
else
{
var attrType = value.GetType();
if (attrType.IsEnum)
strValue = ((int)value).ToString();
else if (attrType == typeof(string))
strValue = StringExt.ToCodeFormat(value as string);
else if (attrType.IsValueType)
strValue = value.ToString();
else
strValue = this.toFriendlyString(value, level + 1);
}
if (dict.Values.Count(x => x[0] == name) == 0)
{
if (order == -1) order = GetNextOrderID(dict);
dict.Add(order, new string[] { name, strValue });
}
}
var kvs = dict.OrderBy(x => x.Key).ToArray();
for (int i = 0; i < kvs.Length; i++)
{
string line;
var kv = kvs[i].Value;
var name = kv[0];
var strValue = kv[1];
if (i < dict.Count - 1)
line = $"{makeMultiSymbol(level + 1)}\"{name}\":{strValue},\r\n";
else
line = $"{makeMultiSymbol(level + 1)}\"{name}\":{strValue}\r\n";
sbLine = new StringBuilder();
sbLine.Append(line);
sbAll.Append(sbLine.ToString());
}
sbLine = new StringBuilder();
sbLine.Append($"{makeMultiSymbol(level)}}}");
sbAll.Append(sbLine.ToString());
}
var result = sbAll.ToString();
return result;
} private string makeMultiSymbol(int count)
{
var symbol = "\t";
var sb = new StringBuilder();
for (int i = 0; i < count; i++)
{
sb.Append(symbol);
}
return sb.ToString();
}
/// <summary>
/// 字节数组转换为Json对象
/// </summary>
/// <param name="b">字节数组</param>
/// <returns>Json对象</returns>
public static T From(byte[] b)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream(b))
{
var o = (T)serializer.ReadObject(ms);
return o;
}
}
/// <summary>
/// 字符串转换为Json对象
/// </summary>
/// <param name="s">字符串</param>
/// <returns>Json对象</returns>
public static T Parse(string s)
{
var b = Encoding.UTF8.GetBytes(s);
var obj = From(b);
return obj;
}
/// <summary>
/// 将Json对象存储为文件
/// </summary>
/// <param name="filePath">保存文件名</param>
/// <param name="friendlyFormat"></param>
public void Write(string filePath, bool friendlyFormat = false)
{
if (File.Exists(filePath)) File.Delete(filePath);
if (friendlyFormat)
{
var s = this.ToFriendlyString();
File.WriteAllText(filePath, s);
}
else
{
var b = this.ToArray();
File.WriteAllBytes(filePath, b);
}
}
/// <summary>
/// 读取指定文件,加载Json对象
/// </summary>
/// <param name="filePath">Json文件路径</param>
/// <returns>Json对象</returns>
public static T Read(string filePath)
{
var s = File.ReadAllText(filePath);
var obj = JsonObject<T>.Parse(s);
return obj;
}
/// <summary>
/// 获取下一个可用的OrderID
/// </summary>
/// <param name="dict">临时存储节点的字典对象</param>
/// <returns>下一个可用的OrderID</returns>
public int GetNextOrderID(Dictionary<int, string[]> dict)
{
int order = 0;
bool unused = false;
while (!unused)
{
var exist = dict.Keys.Any(x => x == order);
if (!exist)
{
unused = true;
}
else
{
order += 1;
}
}
return order;
} }
/// <summary>
/// 字符串扩展
/// </summary>
public static class StringExt
{
/// <summary>
/// 将字符串转换成带转义符的形式
/// </summary>
/// <param name="s">输入字符串</param>
/// <returns></returns>
public static string ToCodeFormat(this string s)
{
s = s.Replace("\\", "\\\\");
s = s.Replace("\b", "\\b");
s = s.Replace("\f", "\\f");
s = s.Replace("\n", "\\n");
s = s.Replace("\r", "\\r");
s = s.Replace("\'", "\\'");
s = s.Replace("\"", "\\\"");
s = s.Replace("\t", "\\t");
s = s.Replace("\0", "\\0");
s = s.Replace("\a", "\\a");
s = s.Replace("\v", "\\v");
return $"\"{s}\"";
}
}
}
Json对象转换模块(自编代码JsonObject.cs)的更多相关文章
- flex 遍历Object或者JSON对象内容的实现代码
private function init():void { //新建对象 var obj:Object = new Object(); //增加key-value obj["name&qu ...
- java对象与json对象间的相互转换
工程中所需的jar包,因为在网上不太好找,所以我将它放到我的网盘里了,如有需要随便下载. 点击下载 1.简单的解析json字符串 首先将json字符串转换为json对象,然后再解析json对象,过程如 ...
- 前后台$.post交互并返回JSON对象
1.前台代码: $.post(url,{"blogId":blogId},function(reData){ if(reData.state=="success" ...
- java链式创建json对象
我们主要介绍一下:java中如何通过最简单的方式实现链式创建json对象,解决创建json代码臃肿的问题. 1.假设我们要创建一个json对象格式如下: { "code": 0, ...
- Android-解析JSON数据(JSON对象/JSON数组)
在上一篇博客中,Android-封装JSON数据(JSON对象/JSON数组),讲解到Android真实开发中更多的是去解析JSON数据(JSON对象/JSON数组) 封装JSON的数据是在服务器端进 ...
- JSON对象与XML相互转换工具类
依赖jar <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId ...
- json对象和json数组
json字符串对象和json字符串数组:JSONArray跟JSONObject的区别就是JSONArray比JSONObject多中括号[] jsonObject: "Row": ...
- android JSONArray JSONObject 字符串转json数组 遍历json对象
String json = "{''data'':[{''name'':''Wallace''},{''name'':''Grommit''}]}"; StringBuffer m ...
- [Json] C#ConvertJson|List转成Json|对象|集合|DataSet|DataTable|DataReader转成Json (转载)
点击下载 ConvertJson.rar 本类实现了 C#ConvertJson|List转成Json|对象|集合|DataSet|DataTable|DataReader转成Json|等功能大家先预 ...
- 类型转换及返回json对象的问题
@ResponseBody @RequestMapping(value="/user/getUserId.do")//method=RequestMethod.POST publi ...
随机推荐
- JDBC之Driver和DriverMananger
JDBC之Driver和DriverMananger 目录 JDBC之Driver和DriverMananger Java和MySQL的关系 JDBC 演变过程 驱动加载入内存的过程 Oracle加载 ...
- js内置方法
数组: 1.push()数组最后添加元素,pop()数组删除最后一个: unshift()数组开头添加元素,shift()删除数字第一个: 注意:push()和unshift()可以添加 ...
- Day 22 22.2:scrapy部署
scrapy项目部署 scrapyd部署工具介绍 scrapyd是一个用于部署和运行scrapy爬虫的程序,它由 scrapy 官方提供的.它允许你通过JSON API来部署爬虫项目和控制爬虫运行. ...
- Java本地缓存解决方案---使用Google的CacheBuilder
一.背景 当业务实现上需要用到本地缓存,来解决一些数据量相对较小但是频繁访问数据的场景,可以采用Google的CacheBuilder解决方案. 二.代码实现 1. 首先在maven中引入下面的包 & ...
- 备份是个好习惯 bugku
题目描述: 解题思路: 1.查看网页源码只显示一行字符,有点像16进制,但经过解码并不是,也不是base64等编码 2.根据题目,应该和备份相关,默认页面一般都是 index.php或者index ...
- vscode - plug - scss转css
vscode - plug - scss转css 参考资料 sass笔记(完结)安装,使用,vscode中设置easy sass,嵌套,变量,混合,循环,分支 vscode配置 easy sass E ...
- curl从入门到精通教程
直接看英文版 https://catonmat.net/cookbooks/curl
- Morris遍历以及Morris前序中序后序遍历实现
#include<iostream> using namespace std; struct TreeNode{ int val; TreeNode* right; TreeNode* l ...
- DorisSQL与MySQL函数对照 差异篇
## 1.日期函数### 时区.```mysql -> convert_tz(dt,from_tz,to_tz)doris -> CONVERT_TZ(DATETIME dt, VARCH ...
- JAVA基础Day2-基本运算符/自增自减运算符/逻辑运算符、位运算符/包机制
一.基本运算符 算术运算符:+.-.*./.%.++.-- 赋值运算符:= 关系运算符:>.<.>=.<=.==.!= instanceof 逻辑运算符:&&. ...