使用 Titanium Android 模块开发将 "List of Objects" 放入 KrollDict

Put "List of Objects" in KrollDict with Titanium Android Module Development

我在模块源代码中声明了自定义 class。

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"]}
]

问题是,如何根据上述示例代码实现预期结果?

使用 GSON 将 List 对象转换为 JSON 字符串并将结果字符串分配给 KrollDict 属性

KrollDict kd = new KrollDict();
Gson gson = new Gson();
String friendListStr = gson.toJson(friendList);
kd.put("friendList", friendListStr);

另一种选择是 return 像这样的对象数组:

KrollDict kd = new KrollDict();
Object[] obj = new Object[friendList.size()];

for (int i=0; i< friendList.size(); ++i){
    KrollDict model = new KrollDict();
    model.put("name", friendList.get(i).name);
    // ...
    obj[i] = model;
}

kd.put("list", obj);
fireEvent("onShow", kd);

这样您的事件中就会有一个数组,以后不需要将该字符串转换为 json。

如果您想使用 JSON,您可以将 TiConverttoJSONtoJSONArraytoJSONString 结合使用,具体取决于您的参数。不需要 Gson。