开发者

convert ArrayList<MyCustomClass> to JSONArray

开发者 https://www.devze.com 2023-02-07 17:59 出处:网络
I have an ArrayList that I use within an ArrayAdapter for a ListView.I need to take the items in the list and convert them to a JSONArray to send to an API. I\'ve searched around, but haven\'t found a

I have an ArrayList that I use within an ArrayAdapter for a ListView. I need to take the items in the list and convert them to a JSONArray to send to an API. I've searched around, but haven't found anything that explains how this might work, any help would be appreciated.

UPDATE - SOLUTION

Here is what I ended up doing to solve the issue.

Object in ArrayList:

public class ListItem {
    private long _masterId;
    private String _name;
    private long _category;

    public ListItem(long masterId, String name, long categ开发者_运维百科ory) {
        _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());
}

And the output:

[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]


If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:

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


Use Gson library to convert ArrayList to JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();


As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);


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();
            }
        }

    }


With kotlin and Gson we can do it more easily:

  1. First, add Gson dependency:

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

  1. 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) {
        null
    }
}

inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)

Note: Do not add declare class, just add these methods, everything will work fine.

  1. Now to call:

create a reference of gson:

val gson=Gson()

To convert array to json string, call:

val jsonString=gson.convertToJsonString(arrayList)

To get array from json string, call:

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

To convert a model to json string, call:

val jsonString=gson.convertToJsonString(model)

To convert json string to model, call:

val model=gson.convertToModel(jsonString, YourModelClassName::class.java)


Add to your gradle:

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

Convert ArrayList to JsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);


I know its already answered, but theres a better solution here use this code :

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

This way you can access variables from class without manually typing them..

Faster and better .. Hope this helps.

Cheers. :D


Here is a solution with jackson:

You could use the ObjectMapper to receive a JSON String and then convert the string to a 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);


Improving on OP's answer when there are a lot of fields. could cut down some code with field enumeration ... ( but know that reflection is slower.)

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) {
            }

        }
        return obj;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号