我是新来的。我正在尝试将复杂对象转换为 XML。
当我尝试遍历对象时遇到问题。我在这里添加代码片段。
创建员工对象
var result:String = new String();
employeeDept = new EmployeeDept();
employee = new Employee();
employee.employeeId = "56789";
employee.employeeName = "XYZ";
//tempString = tempString + "--- Step n ---";
/*employee.employeeDept.deptId = "2";
employee.employeeDept.deptName = "APPLE";*/
employeeDept=new EmployeeDept();
employeeDept.deptId = "3";
employeeDept.deptName = "MS";
employee.employeeDept.addItem(employeeDept);
employeeDept=new EmployeeDept();
employeeDept.deptId = "2";
employeeDept.deptName = "APPLE";
employee.employeeDept.addItem(employeeDept);
empCollection.addItem(employee);
在员工对象上调用转换器方法
recursive(employee, "ShopServiceLifeCycleArtifacts");
转换器方式
public function recursive(obj:Object, str:String):String
{
try
{
var xml:XML=new XML('<' + str + '></' + str + '>' );
if(obj is Array && obj.length!=0)
{ //tempString = tempString + "--- Recursive IF Loop---" + obj.length;
var ac:ArrayCollection=new ArrayCollection(obj as Array);
var xml2:XML=new XML(<dept></dept>);
for (var i:Number=0; i<ac.length; i++)
{
var myObj:Object=ac.getItemAt(i);
for (var prop:String in myObj)
{
xml2.appendChild(new XML("<" + prop + ">" + myObj[prop] + "</" + prop + ">"));
}
}
xml.appendChild(xml2);
} else {
if (obj==null)
tempString = tempString + "--- Obj is null ---";
else
{
tempString = tempString + "--- Obj is not null ---";
}
for (var property:String in obj)
{
tempString = tempString + property;
if(obj[property] is Array)
{
tempString = tempString + "--- obj[property] is Array---";
xml.appendChild(recursive(obj[property] as Array, property));
} else {
tempString = tempString + "--- obj[property] is not Array---";
xml.appendChild(XML("<" + property + ">" + obj[property].toString() + "</" + property + ">"));
}
}
}
}catch(e:Error)
{
return tempString+"----------"+e.message;
}
tempString = tempString +xml.toString();
return xml.toString();
}
}
但现在的问题是,我的员工对象不是一个数组,所以它会进入 else 块。我正在检查对象是否为空。对象不为空。
我要进行下一步,即 for 循环
for (var property:String in obj){
问题来了。它不会进入这个 for 循环并返回 null。:(
而不是在操作脚本文件中创建员工对象并在此处获取该员工的实例,如果我在此处声明并定义一个employeeName 对象,那么逻辑才起作用。我也会显示该代码。
else {
//tempString = tempString + "--- Recursive Else Loop---";
var employeeNew:Object = {employeeId:"123", employeeName:"San Francisco",
empDept :[{empDeptId:"12345", empDeptName:"XYZ"},{empDeptId:"54568", empDeptName:"ABC"}]};
for (var prop:String in employeeNew) {
//trace("myObject."+prop+" = "+employeeNew[prop]);
if(employeeNew[prop] is Array)
{
xml.appendChild(recursive(employeeNew[prop] as Array, prop));
} else {
tempString = tempString + "--- obj[property] is not Array---";
xml.appendChild(XML("<" + prop + ">" + employeeNew[prop].toString() + "</" + prop + ">"));
}
}
如果我使用此对象,它能够将其转换为 XML。请让我知道我在这里做的错误是什么,因为我无法遍历对象。
提前致谢。