2014-09-13 53 views
0

我正在使用這種方法來解析JSON字符串,但它太慢了...有沒有更好的方法來做到這一點? 謝謝在android中解析JSON字符串的更快捷的方法

synchronized private void parseCategories(String response){ 

    try{ 
     JSONArray categoriesJSONArray = new JSONArray (response); 


     // looping through All Contacts 
     for(int i = 0; i < categoriesJSONArray.length(); i++){ 
      JSONObject currentCategory = categoriesJSONArray.getJSONObject(i); 

      String label=""; 
      String categoryId=""; 


      // Storing each json item in variable 
      if(currentCategory.has("label")) 
       label = currentCategory.getString("label"); 


      if(currentCategory.has("id")) 
       categoryId = currentCategory.getString("id"); 

      if(
       label!=null && 
       categoryId!=null 
      ) 
      { 
       Category toAdd = new Category(categoryId, label); 
       categories.add(toAdd); 
      } 

     } 

     //Alphabetic order 
     Collections.sort(
       categories, 
       new Comparator<Feed>() { 
        public int compare(Feed lhs, Feed rhs) { 
         return lhs.getTitle().compareTo(rhs.getTitle()); 
        } 
       } 
     ); 

     Intent intent = new Intent("CategoriesLoaded"); 
     LocalBroadcastManager.getInstance(mAppContext).sendBroadcast(intent); 


    }catch (JSONException e) { 
     e.printStackTrace(); 
    } 

} 
+0

您是否嘗試過使用GSON?我不確定它是否更快,但更方便 – hoomi 2014-09-13 10:53:07

+0

您正在設置label =「」和categoryId =「」,因此它們無法爲空。所以你不最終添加了很多帶有「」作爲標籤和ID的類別嗎? – MTilsted 2014-09-13 10:57:41

+0

儘管答案都不是最快的。 – mmlooloo 2014-09-13 12:44:26

回答

1

以下代碼以代碼開頭。您需要使用Gson庫。

Gson gson=new Gson(); 
MyBean myBean=gson.fromJson(response); 

Note:這裏MyBean類包含你在json字符串中存在的字段,例如, id,以及吸氣和吸氣。其餘全部由Gson負責處理。

下面是一個快速演示。

import com.google.gson.annotations.SerializedName; 

public class Box { 

    @SerializedName("id") 
    private String categoryId; 

    // getter and setter 
} 

說你JSON看起來如下:

{"id":"A12"} 

可以按如下方式對其進行分析:

class Parse{ 
public void parseJson(String response){ 
    Gson gson=new Gson(); 
    Box box=gson.fromJson(response,Box.class); 
    System.out.println(box.getCategoryId()); 
} 
} 

輸出:

A12 

欲瞭解更多Gson訪問here

+0

謝謝,但是如果json字符串中的參數「id」必須插入類的字符串「id_cat」中,我該怎麼辦......有沒有辦法做到這一點? – 2014-09-13 11:34:18

+0

爲他們使用註釋。你可以在類的字段註釋中指定json鍵。 – 2014-09-13 11:36:43

+0

你能舉個例子嗎?謝謝 – 2014-09-13 11:38:40

1

使用GSON庫。您可以將您的對象轉換爲json字符串,如下例所示:

MyClass MyObject; 
Gson gson = new Gson(); 
String strJson = gson.toJson(MyObject);