SORU
30 Ocak 2011, Pazar


dönüştürmek ArrayList<MyCustomClass> JSONArray için

Bir liste Görünümü için bir ArrayAdapter içinde kullandığım bir ArrayList var. Listedeki öğeleri almak istiyorum ve bir API ve göndermek için bir JSONArray onları dönüştürmek. Etrafında aradı, ama bu iş nasıl açıklayan bir şey bulamadım ben, herhangi bir yardım mutluluk duyacağız.

UPDATE - ÇÖZÜM

Kadar bu sorunu çözmek için ben de yapıyordum.

ArrayList nesnesindeki

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

Ben dönüştürülmüş.

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

Ve çıktı:

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

Bu birilerine bir gün yardımcı olur umarım!

CEVAP
30 Ocak 2011, Pazar


Eğer JSONArray doğru kurucular okudum, herhangi bir Tahsilat (arrayList Koleksiyon sınıfı) gibi oluşturabilirsiniz:

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

Referanslar:

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Adam Outler

    Adam Outler

    19 EKİM 2006
  • Hallucination Land

    Hallucinatio

    14 Ocak 2011
  • TheXiaxue

    TheXiaxue

    3 AĞUSTOS 2009