android - 如何将值对象数组转换为json?

标签 android json

我有一组这种类型的类:

 public class IndexVO {
     public int myIndex;
     public String result;
 }

这是我的数组:

     IndexVo[] myArray = { indexvo1, indexvo2 };

我想将这个数组转换为 json,知道怎么做吗?

最佳答案

这不像 JSONArray mJSONArray = new JSONArray(Arrays.asList(myArray)) 那样简单,因为您的数组包含不受支持的类的对象。因此,您将不得不付出更多努力:

JSONArray mJSONArray = new JSONArray();
for (int i = 0; i < myArray.length; i++)
    mJSONArray.put(myArray[i].toJSON());

并将 toJSON() 方法添加到您的 IndexVo 类:

public JSONObject toJSON() {
    JSONObject json = new JSONObject();
    ...
    //here you put necessary data to json object
    ...
    return json;
}

但是,如果您需要为多个类生成 JSON,请考虑自动执行此操作的库,flexjson ,例如。

关于android - 如何将值对象数组转换为json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9207321/

相关文章:

Android - 如何在构建时为开源项目动态设置包名称?

android - 如何在 Windows 8 上调试 Samsung Galaxy S Advanced 上的 Android 应用程序?

java - Android 应用程序和外部数据库之间通信的最佳方式

json - 如何在 bash 脚本中的 curl 中将多行 json 字符串作为正文发布

python - 如果键包含字符串,则删除整个 json 对象

java - java 将字符串中的数字转换为列表

android - 是否所有智能手机浏览器(Android 和 iOS)都支持多点触控/手势?

java - 如何解决导航栏有导航底部问题

Javascript 在点击事件时显示 for 循环中点击的项目

javascript - 在 vue.js 中创建一个包含数据的 obj 名称