init lserp cs 5.0

This commit is contained in:
cyf
2026-07-10 15:25:05 +08:00
commit 90f3fda86a
3799 changed files with 976868 additions and 0 deletions
@@ -0,0 +1,231 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Zhaizj.Framework.ORM;
using Zhaizj.Framework.Reflection;
namespace Zhaizj.Framework.Serialization {
/// <summary>
/// 封装了 json 反序列化中的常见操作:将 json 字符串反序列化为对象、对象列表、字典等。
/// 序列化工具见 JsonString
/// </summary>
public class JSON {
/// <summary>
/// 将字典序列化为 json 字符串
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static String DicToString( Dictionary<String, object> dic ) {
return JsonString.ConvertDictionary( dic, false );
}
//----------------------------------------------------- String to obj ---------------------------------------------------------------------
/// <summary>
/// 将 json 字符串反序列化为对象
/// </summary>
/// <param name="oneJsonString">json 字符串</param>
/// <param name="t">目标类型</param>
/// <returns></returns>
public static Object ToObject( String oneJsonString, Type t ) {
Dictionary<String, object> map = JsonParser.Parse( oneJsonString ) as Dictionary<String, object>;
return setValueToObject( t, map );
}
/// <summary>
/// 将 json 字符串反序列化为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString">json 字符串</param>
/// <returns></returns>
public static T ToObject<T>( String jsonString ) {
Object result = ToObject( jsonString, typeof( T ) );
return (T)result;
}
/// <summary>
/// 将 json 字符串反序列化为对象列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString">json 字符串</param>
/// <returns>返回对象列表</returns>
public static List<T> ToList<T>( String jsonString ) {
List<T> list = new List<T>();
if (strUtil.IsNullOrEmpty( jsonString )) return list;
List<object> lists = JsonParser.Parse( jsonString ) as List<object>;
foreach (Dictionary<String, object> map in lists) {
Object result = setValueToObject( typeof( T ), map );
list.Add( (T)result );
}
return list;
}
internal static Object setValueToObject( Type t, Dictionary<String, object> map ) {
Object result = rft.GetInstance( t );
PropertyInfo[] properties = t.GetProperties( BindingFlags.Public | BindingFlags.Instance );
foreach (KeyValuePair<String, object> pair in map) {
String pName = pair.Key;
String pValue = pair.Value.ToString();
PropertyInfo info = getPropertyInfo( properties, pName );
if ((info != null) && !info.IsDefined( typeof( NotSaveAttribute ), false )) {
Object objValue;
if (ReflectionUtil.IsBaseType( info.PropertyType )) {
objValue = Convert.ChangeType( pValue, info.PropertyType );
}
else if (info.PropertyType == typeof( Dictionary<String, object> )) {
objValue = pair.Value;
}
else if (rft.IsInterface( info.PropertyType, typeof( IList ) )) {
objValue = pair.Value;
}
else {
objValue = rft.GetInstance( info.PropertyType );
ReflectionUtil.SetPropertyValue( objValue, "Id", cvt.ToInt( pValue ) );
}
ReflectionUtil.SetPropertyValue( result, pName, objValue );
}
}
return result;
}
public static IEntity ToEntity( String jsonString, Type t ) {
Dictionary<String, object> map = JsonParser.Parse( jsonString ) as Dictionary<String, object>;
return toEntityByMap( t, map, null );
}
private static IEntity toEntityByMap( Type t, Dictionary<String, object> map, Type parentType ) {
if (map == null) return null;
IEntity result = Entity.New( t.FullName );
EntityInfo ei = Entity.GetInfo( t );
foreach (KeyValuePair<String, object> pair in map) {
String pName = pair.Key;
object pValue = pair.Value;
EntityPropertyInfo p = ei.GetProperty( pName );
Object objValue = null;
if (ReflectionUtil.IsBaseType( p.Type )) {
objValue = Convert.ChangeType( pValue, p.Type );
}
else if (p.IsList) {
continue;
}
else if (pValue is Dictionary<String, object>) {
if (p.Type == parentType) continue;
Dictionary<String, object> dic = pValue as Dictionary<String, object>;
if (dic != null && dic.Count > 0) {
objValue = toEntityByMap( p.Type, dic, t );
}
}
else
continue;
p.SetValue( result, objValue );
}
return result;
}
//--------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// 将 json 字符串反序列化为字典对象的列表
/// </summary>
/// <param name="jsonString"></param>
/// <returns></returns>
public static List<Dictionary<String, object>> ToDictionaryList( String jsonString ) {
List<object> list = JsonParser.Parse( jsonString ) as List<object>;
List<Dictionary<String, object>> results = new List<Dictionary<String, object>>();
foreach (Object obj in list) {
Dictionary<String, object> item = obj as Dictionary<String, object>;
results.Add( item );
}
return results;
}
/// <summary>
/// 将 json 字符串反序列化为字典对象
/// </summary>
/// <param name="oneJsonString"></param>
/// <returns></returns>
public static Dictionary<String, object> ToDictionary( String oneJsonString ) {
String str = trimBeginEnd( oneJsonString, "[", "]" );
if (strUtil.IsNullOrEmpty( str )) return new Dictionary<String, object>();
return JsonParser.Parse( str ) as Dictionary<String, object>;
}
private static String trimBeginEnd( String str, String beginStr, String endStr ) {
str = str.Trim();
str = strUtil.TrimStart( str, beginStr );
str = strUtil.TrimEnd( str, endStr );
str = str.Trim();
return str;
}
private static PropertyInfo getPropertyInfo( PropertyInfo[] propertyList, String pName ) {
foreach (PropertyInfo info in propertyList) {
if (info.Name.Equals( pName )) {
return info;
}
}
return null;
}
/// <summary>
/// 将引号、冒号、逗号进行编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static String Encode( String str ) {
return str.Replace( "\"", "&quot;" ).Replace( ":", "&#58;" ).Replace( ",", "&#44;" ).Replace( "'", "\\'" );
}
/// <summary>
/// 将引号、冒号、逗号进行解码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static String Decode( String str ) {
return str.Replace( "&quot;", "\"" ).Replace( "&#58;", ":" ).Replace( "&#44;", "," ).Replace( "\\'", "'" );
}
}
}
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
/// <summary>
/// json 反序列化工具
/// </summary>
public class JsonParser {
/// <summary>
/// 解析字符串,返回对象。
/// 根据 json 的不同,可能返回整数(int)、布尔类型(bool)、字符串(string)、一般对象(Dictionary&lt;string, object&gt;)、数组(List&lt;object&gt;)等不同类型
/// </summary>
/// <param name="src"></param>
/// <returns>根据 json 的不同,可能返回整数(int)、布尔类型(bool)、字符串(string)、一般对象(Dictionary&lt;string, object&gt;)、数组(List&lt;object&gt;)等不同类型</returns>
public static Object Parse( String src ) {
if (strUtil.IsNullOrEmpty( src )) return null;
return new InitJsonParser( new CharSource(src) ).getResult();
}
}
}
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal class ArrayJsonParser : JsonParserBase {
private List<object> list = new List<object>();
public override Object getResult() {
return list;
}
public ArrayJsonParser( CharSource charSrc )
: base( charSrc ) {
}
protected override void parse() {
charSrc.moveToText();
if (charSrc.getCurrent() != '[') throw ex( "json array must start with [" );
charSrc.moveToText();
if (charSrc.getCurrent() == ']') return;
// 回到[
charSrc.back();
parseOne();
}
private void parseOne() {
charSrc.moveToText();
if (charSrc.getCurrent() == ',') {
charSrc.back();
list.Add( null );
}
else {
charSrc.back();
// 将值加入列表
Object val = moveAndGetParser().getResult();
list.Add( val );
}
// 剩余字符处理
charSrc.moveToText();
char c = charSrc.getCurrent();
if (c == ']') {
return;
}
if (c != ',') throw ex( "json array must seperated with , " );
charSrc.moveToText();
if (charSrc.getCurrent() == ']') {
return;
}
else {
charSrc.back();
parseOne();
}
}
}
}
@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal class CharSource {
public char[] charList;
private int index = -1;
public String strSrc { get; set; }
public CharSource( String src ) {
this.strSrc = clearComment( src );
this.charList = this.strSrc.ToCharArray();
}
private String clearComment( String src ) {
if (src == null) return null;
String[] arr = src.Split( '\n' );
StringBuilder sb = new StringBuilder();
foreach (String line in arr) {
if (line.Trim().StartsWith( "//" )) continue;
sb.Append( line );
sb.AppendLine();
}
return sb.ToString();
}
public char getCurrent() {
return charList[index];
}
public void move() {
if (index >= charList.Length - 1) return;
index++;
}
public void back() {
index--;
}
public void moveToText() {
index++;
char c = this.getCurrent();
if (c == 0 || c > ' ') return;
moveToText();
}
public Boolean isEnd() {
return (index >= charList.Length - 1);
}
public int getIndex() {
return this.index;
}
}
}
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal class InitJsonParser : JsonParserBase {
private Object _result;
public InitJsonParser( CharSource charSrc )
: base( charSrc ) {
}
protected override void parse() {
_result = moveAndGetParser().getResult();
}
public override Object getResult() {
return _result;
}
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal abstract class JsonParserBase {
protected CharSource charSrc;
protected abstract void parse();
public abstract Object getResult();
public JsonParserBase() {
}
public JsonParserBase( CharSource charSrc ) {
this.charSrc = charSrc;
parse();
}
protected JsonParserBase moveAndGetParser() {
charSrc.moveToText();
char c = charSrc.getCurrent();
if (c == '"' || c == '\'') {
return new StringJsonParser( this.charSrc, c );
}
if (c == '{') {
charSrc.back();
return new ObjectJsonParser( this.charSrc );
}
if (c == '[') {
charSrc.back();
return new ArrayJsonParser( this.charSrc );
}
return new ValueJsonParser( this.charSrc );
}
protected JsonParserException ex( String msg ) {
return new JsonParserException( msg + "(index:"+this.charSrc.getIndex().ToString()+")\n" + this.charSrc.strSrc );
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal class JsonParserException : Exception {
private String msg;
public JsonParserException() {
}
public JsonParserException( String msg ) {
this.msg = msg;
}
public JsonParserException( String msg, Exception inner )
: base( msg, inner ) {
}
public override String Message {
get {
return base.Message + Environment.NewLine + this.msg;
}
}
public override String ToString() {
return base.ToString() + Environment.NewLine + this.msg;
}
}
}
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal class ObjectJsonParser : JsonParserBase {
private Dictionary<String, object> map = new Dictionary<String, object>();
public override Object getResult() {
return this.map;
}
public ObjectJsonParser( CharSource charSrc )
: base( charSrc ) {
}
protected override void parse() {
charSrc.moveToText();
if (charSrc.getCurrent() != '{') throw ex( "json Object must start with { " );
charSrc.moveToText();
if (charSrc.getCurrent() == '}') return;
charSrc.back();
parseOne();
}
private void parseOne() {
charSrc.moveToText();
if (charSrc.getCurrent() == '}') return;
// 解析key
charSrc.back();
String key = moveAndGetParser().getResult().ToString();
// 解析冒号
charSrc.moveToText();
if (charSrc.getCurrent() != ':') throw ex( "json object's property pair must seperated with :" );
// 解析value
Object val = moveAndGetParser().getResult();
// 获取值
map.Add( key, val );
// 处理剩下的字符
charSrc.moveToText();
char c = charSrc.getCurrent();
if (c == '}') return;
if (c != ',') throw ex( "json object's property must seperated with ," );
charSrc.moveToText();
if (charSrc.getCurrent() == '}')
return;
else {
charSrc.back();
parseOne();
}
}
}
}
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal class StringJsonParser : ValueJsonParser {
private String _result;
public override Object getResult() {
return _result;
}
public StringJsonParser( CharSource charSrc, char c ) {
this.quote = c;
this.charSrc = charSrc;
parse();
}
private char quote = '"';
protected override void parse() {
charSrc.move();
char c = charSrc.getCurrent();
if (c == '\n' || c == '\r') throw ex( "String ends at a new line while not end" );
if (c == quote) {
_result = sb.ToString();
return;
}
if (c == '\\')
processEscape();
else
sb.Append( c );
parse();
}
}
}
@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhaizj.Framework.Serialization {
internal class ValueJsonParser : JsonParserBase {
protected StringBuilder sb = new StringBuilder();
private static readonly String separatorChars = ",\":[]{}";
private Object _result;
public override Object getResult() {
return _result;
}
public ValueJsonParser() {
}
public ValueJsonParser( CharSource charSrc )
: base( charSrc ) {
}
protected override void parse() {
paserOne();
charSrc.back();
String s = sb.ToString().Trim();
if (s.Equals( "" )) throw ex( "value is empty" );
_result = getStringValue( s );
}
private void paserOne() {
char c = charSrc.getCurrent();
if (c >= ' ' && separatorChars.IndexOf( c ) < 0) {
if (c == '\\') {
processEscape();
}
else
sb.Append( c );
if (charSrc.isEnd()) return;
charSrc.move();
paserOne();
}
}
protected void processEscape() {
charSrc.move();
char c = charSrc.getCurrent();
if (c == 'b')
sb.Append( '\b' );
else if (c == 't')
sb.Append( '\t' );
else if (c == 'n')
sb.Append( '\n' );
else if (c == 'n')
sb.Append( '\n' );
else if (c == 'r')
sb.Append( '\r' );
else if (c == 'u') {
//sb.Append( '' ); // TODO
}
else if (c == '"' || c == '\'' || c == '/' || c == '\\')
sb.Append( c );
else
throw ex( "not a valid escape character" );
}
private static Object getStringValue( String s ) {
if (cvt.IsInt( s )) return cvt.ToInt( s );
if (cvt.IsDecimal( s )) return cvt.ToDecimal( s );
if (cvt.IsBool( s )) return cvt.ToBool( s );
return s;
}
}
}
@@ -0,0 +1,323 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Reflection;
using Zhaizj.Framework.Reflection;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Serialization {
/// <summary>
/// json 序列化工具:将对象转换成 json 字符串
/// </summary>
public class JsonString {
private static Boolean getDefaultIsBreakline() {
return false;
}
private static String empty() {
return "\"\"";
}
/// <summary>
/// 将对象转换成 json 字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static String Convert( Object obj ) {
return Convert( obj, getDefaultIsBreakline() );
}
/// <summary>
/// 将对象转换成 json 字符串
/// </summary>
/// <param name="obj"></param>
/// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
/// <returns></returns>
public static String Convert( Object obj, Boolean isBreakline ) {
if (obj == null) return empty();
Type t = obj.GetType();
if (t.IsArray) return ConvertArray( (object[])obj );
if (rft.IsInterface( t, typeof( IList ) )) return ConvertList( (IList)obj );
if (rft.IsInterface( t, typeof( IDictionary ) )) return ConvertDictionary( (IDictionary)obj, isBreakline );
if (t == typeof( int ) ||
t == typeof( decimal ) ||
t == typeof( double )) {
return obj.ToString();
}
if (t == typeof( Boolean )) return obj.ToString().ToLower();
if (t == typeof( DateTime )) return "\"" + obj.ToString() + "\"";
if (t == typeof( String )) {
// 转义双引号,消除换行
return "\"" + ClearNewLine( obj.ToString() ) + "\"";
}
return ConvertObject( obj, isBreakline );
}
/// <summary>
/// 清楚json字符串中的换行符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static String ClearNewLine( String str ) {
if (str == null) return null;
return str
.Replace( @"\", @"\\" )
.Replace( "\"", "\\" + "\"" )
.Replace( "\r", "" )
.Replace( "\n", "" )
.Replace( "\t", "" );
}
/// <summary>
/// 将对象数组转换成 json 字符串
/// </summary>
/// <param name="arrObj"></param>
/// <returns></returns>
public static String ConvertArray( object[] arrObj ) {
if (arrObj == null) return "[]";
StringBuilder sb = new StringBuilder();
sb.Append( "[ " );
for (int i = 0; i < arrObj.Length; i++) {
if (arrObj[i] == null) continue;
sb.Append( Convert( arrObj[i], getDefaultIsBreakline() ) );
if (i < arrObj.Length - 1) sb.Append( ", " );
}
sb.Append( " ]" );
return sb.ToString();
}
/// <summary>
/// 将对象列表转换成 json 字符串
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static String ConvertList( IList list ) {
return ConvertList( list, getDefaultIsBreakline() );
}
/// <summary>
/// 将对象列表转换成 json 字符串
/// </summary>
/// <param name="list"></param>
/// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
/// <returns></returns>
public static String ConvertList( IList list, Boolean isBreakline ) {
if (list == null) return "[]";
StringBuilder sb = new StringBuilder();
sb.Append( "[ " );
if (isBreakline) sb.AppendLine();
for (int i = 0; i < list.Count; i++) {
if (list[i] == null) continue;
sb.Append( Convert( list[i], isBreakline ) );
if (i < list.Count - 1) sb.Append( ", " );
if (isBreakline) sb.AppendLine();
}
sb.Append( " ]" );
return sb.ToString();
}
/// <summary>
/// 将字典 Dictionary 转换成 json 字符串
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static String ConvertDictionary( IDictionary dic ) {
return ConvertDictionary( dic, getDefaultIsBreakline() );
}
/// <summary>
/// 将字典 Dictionary 转换成 json 字符串
/// </summary>
/// <param name="dic"></param>
/// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
/// <returns></returns>
public static String ConvertDictionary( IDictionary dic, Boolean isBreakline ) {
if (dic == null) return empty();
StringBuilder builder = new StringBuilder();
builder.Append( "{ " );
if (isBreakline) builder.AppendLine();
foreach (DictionaryEntry pair in dic) {
builder.Append( "\"" );
builder.Append( pair.Key );
builder.Append( "\":" );
builder.Append( Convert( pair.Value, isBreakline ) );
builder.Append( ", " );
if (isBreakline) builder.AppendLine();
}
String result = builder.ToString().Trim().TrimEnd( ',' );
if (isBreakline) result += Environment.NewLine;
return result + " }";
}
/// <summary>
/// 将对象转换成 json 字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static String ConvertObject( Object obj ) {
return ConvertObject( obj, getDefaultIsBreakline() );
}
/// <summary>
/// 将对象转换成 json 字符串
/// </summary>
/// <param name="obj"></param>
/// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
/// <returns></returns>
public static String ConvertObject( Object obj, Boolean isBreakline ) {
return ConvertObject( obj, isBreakline, true );
}
/// <summary>
/// 将对象转换成 json 字符串
/// </summary>
/// <param name="obj"></param>
/// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
/// <param name="withQuotation">属性名是否使用引号(默认不启用)</param>
/// <returns></returns>
public static String ConvertObject( Object obj, Boolean isBreakline, Boolean withQuotation ) {
StringBuilder builder = new StringBuilder();
builder.Append( "{ " );
if (isBreakline) builder.AppendLine();
PropertyInfo[] properties = obj.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance );
Boolean isIdFind = false;
Boolean isNameFind = false;
Object idValue = "";
Object nameValue = "";
List<PropertyInfo> propertyList = new List<PropertyInfo>();
foreach (PropertyInfo info in properties) {
if (info.Name.Equals( "Id" )) {
isIdFind = true;
idValue = ReflectionUtil.GetPropertyValue( obj, "Id" );
}
else if (info.Name.Equals( "Name" )) {
isNameFind = true;
nameValue = ReflectionUtil.GetPropertyValue( obj, "Name" );
}
else {
propertyList.Add( info );
}
}
if (withQuotation) {
if (isIdFind) builder.AppendFormat( "\"Id\":{0}, ", idValue );
if (isNameFind) builder.AppendFormat( "\"Name\":\"{0}\", ", nameValue );
}
else {
if (isIdFind) builder.AppendFormat( "Id:{0}, ", idValue );
if (isNameFind) builder.AppendFormat( "Name:\"{0}\", ", nameValue );
}
foreach (PropertyInfo info in propertyList) {
if (info.IsDefined( typeof( NotSerializeAttribute ), false )) {
continue;
}
Object propertyValue = ReflectionUtil.GetPropertyValue( obj, info.Name );
String jsonValue;
if (info.PropertyType.IsArray) {
jsonValue = ConvertArray( (object[])propertyValue );
}
else if (rft.IsInterface( info.PropertyType, typeof( IList ) )) {
jsonValue = ConvertList( (IList)propertyValue, isBreakline );
}
else {
jsonValue = Convert( propertyValue, isBreakline );
}
if (withQuotation) {
builder.AppendFormat( "\"{0}\":{1}", info.Name, jsonValue );
}
else {
builder.AppendFormat( "{0}:{1}", info.Name, jsonValue );
}
builder.Append( ", " );
if (isBreakline) builder.AppendLine();
}
String result = builder.ToString().Trim().TrimEnd( ',' );
if (isBreakline) result += Environment.NewLine;
return result + " }";
}
public static String ConvertEntity( IEntity obj ) {
StringBuilder builder = new StringBuilder();
builder.Append( "{ " );
EntityInfo ei = Entity.GetInfo( obj );
List<EntityPropertyInfo> ps = ei.PropertyListAll;
foreach (EntityPropertyInfo info in ps) {
if (shouldPass( info )) continue;
Object propertyValue = info.GetValue( obj );
String jsonValue;
if (propertyValue == null) {
jsonValue = empty();
}
else {
if (info.IsEntity) {
jsonValue = ConvertEntity( propertyValue as IEntity );
}
else
jsonValue = Convert( propertyValue, false );
}
builder.AppendFormat( "{0}:{1}", info.Name, jsonValue );
builder.Append( ", " );
}
String result = builder.ToString().Trim().TrimEnd( ',' );
return result + " }";
}
private static bool shouldPass( EntityPropertyInfo info ) {
if (info.Type == typeof( int )) return false;
if (info.Type == typeof( string )) return false;
if (info.Type == typeof( decimal )) return false;
if (info.Type == typeof( DateTime )) return false;
if (info.Type == typeof( bool )) return false;
if (info.Type == typeof( double )) return false;
if (info.IsEntity) return false;
return true;
}
}
}
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Reflection;
using Zhaizj.Framework.Reflection;
using Zhaizj.Framework.ORM;
namespace Zhaizj.Framework.Serialization {
/// <summary>
/// 将简单的对象转换成 json 字符串,不支持子对象(即属性为对象)的序列化
/// </summary>
public class SimpleJsonString {
/// <summary>
/// 将对象列表转换成 json 字符串
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static String ConvertList( IList list ) {
StringBuilder sb = new StringBuilder( "[\r\n" );
for (int i = 0; i < list.Count; i++) {
sb.Append( "\t" );
sb.Append( ConvertObject( list[i] ) );
if (i < list.Count - 1)
sb.Append( "," );
sb.Append( "\r\n" );
}
sb.Append( "]" );
return sb.ToString();
}
/// <summary>
/// 将对象转换成 json 字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static String ConvertObject( Object obj ) {
StringBuilder builder = new StringBuilder();
builder.Append( "{ " );
PropertyInfo[] properties = obj.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance );
Boolean isIdFind = false;
Boolean isNameFind = false;
Object idValue = "";
Object nameValue = "";
IList propertyList = new ArrayList();
foreach (PropertyInfo info in properties) {
if (info.Name.Equals( "Id" )) {
isIdFind = true;
idValue = ReflectionUtil.GetPropertyValue( obj, "Id" );
}
else if (info.Name.Equals( "Name" )) {
isNameFind = true;
nameValue = ReflectionUtil.GetPropertyValue( obj, "Name" );
}
else {
propertyList.Add( info );
}
}
if (isIdFind) builder.AppendFormat( "Id:{0}, ", idValue );
if (isNameFind) builder.AppendFormat( "Name:\"{0}\", ", nameValue );
foreach (PropertyInfo info in propertyList) {
if (info.IsDefined( typeof( NotSerializeAttribute ), false )) {
continue;
}
if (info.IsDefined( typeof( NotSaveAttribute ), false )) {
continue;
}
Object propertyValue = ReflectionUtil.GetPropertyValue( obj, info.Name );
if ((info.PropertyType == typeof( int )) || (info.PropertyType == typeof( decimal ))) {
builder.AppendFormat( "{0}:{1}", info.Name, propertyValue );
}
else if (info.PropertyType == typeof( Boolean )) {
builder.AppendFormat( "{0}:{1}", info.Name, propertyValue.ToString().ToLower() );
}
else if (ReflectionUtil.IsBaseType( info.PropertyType )) {
builder.AppendFormat( "{0}:\"{1}\"", info.Name, EncodeQuoteAndClearLine( strUtil.ConverToNotNull( propertyValue ) ) );
}
else {
Object str = ReflectionUtil.GetPropertyValue( propertyValue, "Id" );
builder.AppendFormat( "{0}:\"{1}\"", info.Name, EncodeQuoteAndClearLine( strUtil.ConverToNotNull( str ) ) );
}
builder.Append( ", " );
}
return (builder.ToString().Trim().TrimEnd( ',' ) + " }");
}
private static String EncodeQuoteAndClearLine( String src ) {
//return src.Replace( "\"", "\\\"" ).Replace( "\r\n", "" ).Replace( "\n", "" ).Replace( "\r", "" ).Replace( "\r\n", "" );
return JsonString.ClearNewLine( src );
}
}
}