Menu

#2 Add support for objects

open
nobody
5
2007-02-21
2007-02-21
viperjason
No

I know its not that hard. I need to serialize some objects in C# so I added a basic support. It doesnt conform to PHP standards, but it worked for my requirement. I hope you could implement something like it that was PHP standard.
In function deserialize:
case 'o':
{
string objType;
int i;
start = str.IndexOf(":", this.pos) + 1;
end = str.IndexOf(":", start);
objType = str.Substring(start, end - start);
int strlenEnd = str.IndexOf(":", end+1);
stLen = str.Substring(end + 1, strlenEnd - end - 1);
length = int.Parse(stLen);
start = str.IndexOf("{", end);
for (i = 0; i < length; i++)
end = str.IndexOf("}", end+1);
string tmp = str.Substring(start + 1, end - start + 1);
i = 0;
ConstructorInfo ci = Type.GetType(objType).GetConstructor(new Type[] { });
object obj = ci.Invoke(null);
this.pos = end;
int varStart = 0;
int varEnd = 0;
while (i < length)
{
varEnd = tmp.IndexOf(":",varStart);
string varName = tmp.Substring(varStart, varEnd - varStart);
varStart = varEnd + 2; //:{
varEnd = tmp.IndexOf("}", varStart);
string varValue = tmp.Substring(varStart, varEnd - varStart);
this.pos = 0;
varStart = varEnd + 2; //};
object varRealValue = this.deserialize(varValue);
if (varRealValue != null)
obj.GetType().GetProperty(varName).SetValue(obj, varRealValue , null);
i++;
}
this.pos = end + 4; //};};
return obj;
}

In function serialize:

else if (obj is Object)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
sb.Append("o:" + obj.GetType().FullName + ":" + properties.Length + ":{");
foreach (PropertyInfo item in properties)
{
sb.Append(item.Name + ":{" + this.serialize(item.GetValue(obj, null)) + "};");
}
sb.Append("};");
return sb;
}

Reflection is your friend.

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.