我在模块源代码中声明了一个自定义类。
public class Friend{
public String name;
public List<String> phoneNumbers;
public List<String> emailAddresses;
public Friend(String name, List<String>emailAddresses,
List<String>phoneNumbers){
this.name = name;
this.emailAddresses = emailAddresses;
this.phoneNumbers = phoneNumbers;
}
}
我在模块中声明了一个Android方法
@Kroll.method
protected synchronized void getListOfObjects(){
List<String> emailAddresses = Arrays.asList("email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com");
List<String> phoneNumbers = Arrays.asList("1", "2", "3");
List<Friend> friendList = new ArrayList<Friend>();
friendList.add(new Friend("test1", emailAddresses, phoneNumbers));
friendList.add(new Friend("test2", emailAddresses, phoneNumbers));
friendList.add(new Friend("test3", emailAddresses, phoneNumbers));
KrollDict kd = new KrollDict();
kd.put("friendList", friendList);
if (hasListeners("onShow")) {
fireEvent("onShow", kd);
}
}
在Titanium App中调用getListOfOjects方法
module.getListOfObjects();
module.addEventListener('onShow', function(e){
Ti.API.info(JSON.stringify(e.friendList));
});
我似乎无法检索friendList对象。
我想要实现的预期结果将是这样的
[
{test1, ["email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com"], ["1", "2", "3"]},
{test2, ["email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com"], ["1", "2", "3"]},
{test3, ["email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com"], ["1", "2", "3"]}
]
问题是,如何根据上面的示例代码实现预期结果?
答案 0 :(得分:0)
使用GSON将List对象转换为JSON字符串,并将结果字符串分配给KrollDict属性
KrollDict kd = new KrollDict();
Gson gson = new Gson();
String friendListStr = gson.toJson(friendList);
kd.put("friendList", friendListStr);