我的android应用程序必须解析几种类型的json文本,例如下面的例子。Java(Android) - Json解析器的最佳类示例是什么?
{
"text": "Hello World !",
"site": "http://helloworld.com"
}
所以我想做一个类来管理这个应用程序必须解析的每个json文本。像一个“JsonUtil.java”
我做了这样的课。
public class JsonUtil {
public static final String TAG = JsonUtil.class.getSimpleName();
public JsonUtil() {
}
public NotificationAd parseNotificationAd(JSONObject jsonObject) {
NotificationAd notificationAd = new NotificationAd();
try {
notificationAd.message = jsonObject.getString("text");
notificationAd.targetUrl = jsonObject.getString("site");
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "parseNotificationAd, notificationAd: " + notificationAd.toString());
return notificationAd;
}
public class NotificationAd {
public String message;
public String targetUrl;
@Override
public String toString() {
return String.format("message: %s, targetUrl: %s", message, targetUrl);
}
}
}
我使用嵌套类太多“VO.java”类可以刺激总包结构的原因(我不知道为什么,只是我的口味:P太多的课让我复杂。)
所以用法是这样的,
JsonUtil.NotificationAd notificationAd = new JsonUtil().parseNotificationAd(response);
String message = notificationAd.message;
String targetUrl = notificationAd.targetUrl;
我想知道如果我是正确的,其实我想要做班级为“抽象”,并使法“静态”像下面。
public abstract class JsonUtil {
public static final String TAG = JsonUtil.class.getSimpleName();
public static NotificationAd parseNotificationAd(JSONObject jsonObject) {
NotificationAd notificationAd = new NotificationAd();
try {
notificationAd.message = jsonObject.getString("text");
notificationAd.targetUrl = jsonObject.getString("site");
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "parseNotificationAd, notificationAd: " + notificationAd.toString());
return notificationAd;
}
public static class NotificationAd {
public String message;
public String targetUrl;
@Override
public String toString() {
return String.format("message: %s, targetUrl: %s", message, targetUrl);
}
}
}
但我认为下一个代码有一些内存问题(这一点是我需要一些帮助,我不是专业的JAVA)。
任何人都可以建议哪些是在Android的Json解析器的最佳做法?
(我知道改装库,但PLZ别提了这样一个问题:P)
非常感谢每一个答案!
你可以使用GSON序列化和反序列化JSON。 – motiver
你可以试试Gson或Jackson。 –
@motiver vipul_asri你可以给我一些示例代码吗? – wonsuc