【问题标题】:Put "List of Objects" in KrollDict with Titanium Android Module Development使用 Titanium Android 模块开发将“对象列表”放入 KrollDict
【发布时间】:2017-11-12 09:09:59
【问题描述】:

我在模块源代码中声明了一个自定义类。

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 应用程序中调用 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"]}
]

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

【问题讨论】:

    标签: titanium titanium-mobile appcelerator-titanium titanium-modules titanium-android


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      另一种选择是返回一个像这样的对象数组:

      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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-29
        • 1970-01-01
        • 2020-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多