java - 在 Android 中解析 JSON 字符串的更快方法

标签 java android json parsing

我正在使用这种方法来解析 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();
    }

}

最佳答案

这里尝试从以下代码开始。您需要 Gson 库。

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

注意: 这里 MyBean 类包含 json 字符串中存在的字段,例如id,以及 getter 和 setter。其余的一切由 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

关于java - 在 Android 中解析 JSON 字符串的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25822433/

相关文章:

java - @Post Jersey 在带有 javax.ws.rs.POST 注释的方法中只允许有一个未注释的参数

java - 约束布局在不同设备上执行不同

java - 如何在SpringSource Tool Suite中创建Roo Shell项目?

android - 如何编写自己的复制和粘贴上下文菜单?

java - 将变量放入 json 文本正文中

JavaSparkContext 不可序列化

java - JSON 没有标识符,我如何从中获取信息?

android - 在 Ionic 中使用叠加图像录制视频

javascript - 如何将 JSON 字符串分配给 Javascript 变量?

javascript - 在 Node.js 中的字典上调用 forEach