gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:27:57 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com