添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
光明磊落的毛巾  ·  Spock in Java ...·  1 年前    · 

将ArrayList<MyCustomClass>转换为JSONArray

134 人关注

我有一个ArrayList,我在ListView的ArrayAdapter中使用。 我需要将列表中的项目转换为JSONArray,并将其发送给API。我到处搜索,但没有找到任何东西可以解释这一点,希望能得到任何帮助。

更新--解决方案

以下是我最终为解决这个问题所做的工作。

ArrayList中的对象。

public class ListItem {
    private long _masterId;
    private String _name;
    private long _category;
    public ListItem(long masterId, String name, long category) {
        _masterId = masterId;
        _name = name;
        _category = category;
    public JSONObject getJSONObject() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("Id", _masterId);
            obj.put("Name", _name);
            obj.put("Category", _category);
        } catch (JSONException e) {
            trace("DefaultListItem.toString JSONException: "+e.getMessage());
        return obj;

Here is how I converted it:

ArrayList<ListItem> myCustomList = .... // list filled with objects
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
        jsonArray.put(myCustomList.get(i).getJSONObject());

还有输出。

[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]
    
android
arraylist
arrays
json
pmko
pmko
发布于 2011-01-30
9 个回答
Nanne
Nanne
发布于 2022-09-08
已采纳
0 人赞同

如果我对JSONArray构造函数的理解是正确的,你可以像这样从任何集合(arrayList是Collection的子类)中建立它们。

ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);

References:

  • jsonarray constructor: http://developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29
  • collection: http://developer.android.com/reference/java/util/Collection.html
  • pmko
    这在你的例子中是可行的,但在我的例子中,ArrayList是由Objects而不是Strings组成的--我想我应该在我的问题中说明这一点。 我想这是正确的方向,但我可能需要在我的类中覆盖toString以使其正确工作。
    你可以一直在你的列表上循环,并使用jsArray.put()来做这个。最后你的对象应该有一个toString方法,以便将它们转换为JSONArray,我想,因为它们会被保存为一个。
    pmko
    这让我接近了,但发生的情况是,每个对象的toString()输出被作为一个字符串插入JSONArray中。 最后我还是得到了一个字符串的JSONArray,而不是对象。 我最终在我的类上创建了一个名为getJSONObject的方法,然后在ArrayList上循环,并将其结果放入JSONArray中。 谢谢你让我走上了正确的道路。 我打算接受你的回答,然后贴出我最后做的代码样本。我希望这不是坏的SO礼仪。
    Purushotham
    Purushotham
    发布于 2022-09-08
    0 人赞同

    使用Gson库将ArrayList转换为JsonArray。

    Gson gson = new GsonBuilder().create();
    JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
        
    nima
    这不是OP想要的org.json.JSONArray,而是com.google.gson.JsonArray。
    在使用Gson.toJsonTree时,还有一个Id文件被自动添加。
    @HiteshKamani 它不会自动添加一个额外的id,可能你的类有一个id字段。
    这实际上取决于任务。一般来说,不值得用整个外部库来做android SDK自己能做的事情。特别是当你的项目处于64K方法的边缘时。
    嗨,UTTAM,很好的解决方案,只是有一点,它没有把arraylist中的arraylist转换成json数组。
    zionpi
    zionpi
    发布于 2022-09-08
    0 人赞同

    当有人发现OP想把自定义列表转换为 org.json.JSONArray 而不是 com.google.gson.JsonArray 的时候,就会发现。 CORRECT 答案应该是这样的。

    Gson gson = new Gson();
    String listString = gson.toJson(
                        targetList,
               new TypeToken<ArrayList<targetListItem>>() {}.getType());
     JSONArray jsonArray =  new JSONArray(listString);
        
    真棒 :)你是完美的
    @zionpi 这里有两个库被用来将数组列表转换为Json数组
    @Uttam 你在哪里可以看到这里面使用的两个lib?
    如果我没有猜错的话,JSONArray来自org.json,Gson来自com.google.json。
    Gah这抛出了检查过的异常。JSONException。否则,完美的答案就在这里。
    dhamat chetan
    dhamat chetan
    发布于 2022-09-08
    0 人赞同
    public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {
            JSONObject jResult = new JSONObject();// main object
            JSONArray jArray = new JSONArray();// /ItemDetail jsonArray
            for (int i = 0; i < list.size(); i++) {
                JSONObject jGroup = new JSONObject();// /sub Object
                try {
                    jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
                    jGroup.put("ID", list.get(i).get("id"));
                    jGroup.put("Name", list.get(i).get("name"));
                    jGroup.put("Category", list.get(i).get("category"));
                    jArray.put(jGroup);
                    // /itemDetail Name is JsonArray Name
                    jResult.put("itemDetail", jArray);
                    return jResult;
                } catch (JSONException e) {
                    e.printStackTrace();
        
    C--
    这是我成为一个懒惰的程序员的原因之一。我从SOF获得了做事情的胶囊大小的代码。复制粘贴,一切都能成功。不知道我什么时候会被一个能做同样事情的机器人所取代......
    Suraj Vaishnav
    Suraj Vaishnav
    发布于 2022-09-08
    0 人赞同

    有了kotlin和Gson,我们可以更容易地做到这一点。

  • First, add Gson dependency:
  • implementation "com.squareup.retrofit2:converter-gson:2.3.0"

  • Create a separate kotlin file, add the following methods
  • import com.google.gson.Gson
    import com.google.gson.reflect.TypeToken
    fun <T> Gson.convertToJsonString(t: T): String {
        return toJson(t).toString()
    fun <T> Gson.convertToModel(jsonString: String, cls: Class<T>): T? {
        return try {
            fromJson(jsonString, cls)
        } catch (e: Exception) {
    inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)
    

    注意:不要添加声明类,只要添加这些方法,一切都会顺利进行。

  • Now to call:
  • 创建一个gson的引用。

    val gson=Gson()

    要将数组转换为json字符串,请调用:

    val jsonString=gson.convertToJsonString(arrayList)
    

    要从json字符串中获得数组,调用:

    val arrayList=gson.fromJson<ArrayList<YourModelClassName>>(jsonString)
    

    要将一个模型转换为json字符串,请调用。

    val jsonString=gson.convertToJsonString(model)
    

    要将json字符串转换为模型,请调用。

    val model=gson.convertToModel(jsonString, YourModelClassName::class.java)
        
    Deep Patel
    Deep Patel
    发布于 2022-09-08
    0 人赞同

    添加到你的gradle中。

    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    

    Convert ArrayList to JsonArray

    JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
        
    ralphgabb
    ralphgabb
    发布于 2022-09-08
    0 人赞同

    我知道它已经回答了,但这里有一个更好的解决方案,使用这个代码。

    for ( Field f : context.getFields() ) {
         if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
               //DO String To JSON
         /// And so on...
    

    这样,你可以从类中访问变量,而不需要手动输入。

    更快、更好. 希望这有帮助。

    Cheers. :D

    Deniz Husaj
    Deniz Husaj
    发布于 2022-09-08
    0 人赞同

    这里有一个与杰克逊的解决方案。

    你可以使用ObjectMapper来接收一个JSON字符串,然后将字符串转换成JSONArray。

    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.json.JSONArray;
    List<CustomObject> myList = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(myList);
    JSONArray jsonArray = new JSONArray(jsonString);
        
    zingh
    zingh
    发布于 2022-09-08
    0 人赞同

    当有很多字段时,对OP的回答进行改进。 可以用字段枚举来减少一些代码......(但要知道,反射会更慢。)

    public JSONObject getJSONObject() {
            JSONObject obj = new JSONObject();
            Field[] fields = ListItem.class.getDeclaredFields();
            for (Field f : fields) {
                try {
                    obj.put(f.getName(), f.get(ListItem.this));
                } catch (JSONException | IllegalAccessException e) {