簡體   English   中英

需要 GSON 返回一個 Java JSONArray

[英]need GSON to return a Java JSONArray

我無法返回 JSONArray,而我的 object 似乎是一個字符串。 myArray的值與jsonString的值相同。 object 是字符串 object 而不是JSONArray 以及jsonStringmyArray prnt:

[{"id":"100002930603211",
  "name":"Aardvark Jingleheimer",
  "picture":"shortenedExample.jpg" },
 {"id":"537815695",
   "name":"Aarn Mc",
   "picture":"shortendExample.jpg" },
 {"id":"658471072",
   "name":"Adrna opescu",
   "picture":"shortenedExample.jpg"
}]

如何將其轉換為實際的 Java JSONArray 謝謝!

           //arrPersons is an ArrayList

        Gson gson = new Gson();
        String jsonString = gson.toJson(arrPersons);

        JsonParser parser = new JsonParser();
        JsonElement myElement = parser.parse(jsonString);
        JsonArray myArray = myElement.getAsJsonArray();

我認為你可以做你想做的事而無需寫出 json 字符串然后重新讀取它:

List<Person> arrPersons = new ArrayList<Person>();

// populate your list

Gson gson = new Gson();
JsonElement element = gson.toJsonTree(arrPersons, new TypeToken<List<Person>>() {}.getType());

if (! element.isJsonArray()) {
// fail appropriately
    throw new SomeException();
}

JsonArray jsonArray = element.getAsJsonArray();
    public JSONArray getMessage(String response){

    ArrayList<Person> arrPersons = new ArrayList<Person>();
    try {
        // obtain the response
        JSONObject jsonResponse = new JSONObject(response);
        // get the array
        JSONArray persons=jsonResponse.optJSONArray("data");


        // iterate over the array and retrieve single person instances
        for(int i=0;i<persons.length();i++){
            // get person object
            JSONObject person=persons.getJSONObject(i);
            // get picture url
            String picture=person.optString("picture");
            // get id
            String id=person.optString("id");
            // get name
            String name=person.optString("name");

            // construct the object and add it to the arraylist
            Person p=new Person();
            p.picture=picture;
            p.id=id;
            p.name=name;
            arrPersons.add(p);
        }
        //sort Arraylist
        Collections.sort(arrPersons, new PersonSortByName());


    Gson gson = new Gson();
    //gson.toJson(arrPersons);

    String jsonString = gson.toJson(arrPersons);

    sortedjsonArray = new JSONArray(jsonString);



    } catch (JSONException e) {

        e.printStackTrace();
    }

    return sortedjsonArray;

}



public class PersonSortByName implements Comparator<Person>{

    public int compare(Person o1, Person o2) {
    return o1.name.compareTo(o2.name);
    }
    }

  public class Person{
       public String picture;
       public String id;
       public String name;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM