2012-04-04 57 views
4

我不能够返回一个JSONArray,而是我的对象看起来是一个String。 myArray的值与jsonString的值相同。该对象是一个String对象,而不是一个JSONArray。两者jsonStringmyArray的 PRNT:需要GSON返回一个Java JSONArray

[{"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(); 
+0

这不可能是正确的。 getAsJsonArray()返回一个JSONArray。 Java是静态类型的,如果myArray实际上不是JsonArray,那么你上面写的东西不会编译。 – Max 2012-04-04 23:39:52

+0

这是我的问题的一部分。 Gson JsonArray对象与Java JSONArray对象不同。我想创建一个JSONArray。 – Tom 2012-04-05 00:28:29

+1

?没有* Java JSONArray对象。你的意思是来自http://json.org的JSONArray? – Max 2012-04-05 01:19:59

回答

1

我认为你可以做你想做的,而无需编写了一个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(); 
0
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; 
    }