【发布时间】:2017-01-25 08:03:54
【问题描述】:
以下是我想在我的 iOS (Swift) 和 Android (Java) 应用程序中使用的 JSON 正文。
{
"type" : "select",
"args" : {
"table" : "todo",
"columns": ["id", "title","completed"],
"where" : {"user_id": 1}
}
}
在 Swift 中,将上述内容转换为字典非常简单:
let params: [String: Any] = [
"type" : "select",
"args" : [
"table" : "todo",
"columns" : ["id","title","completed"],
"where" : ["user_id" : 1]
]
]
在Java中,我是使用GSON来做上面的,但是我觉得我的解决方案很丑,太长了
public class SelectQuery {
@SerializedName("type")
String type = "select";
@SerializedName("args")
Args args;
public SelectTodoQuery(=) {
args = new Args();
args.where = new Where();
args.where.userId = 1;
}
class Args {
@SerializedName("table")
String table = "todo";
@SerializedName("columns")
String[] columns = {
"id","title","completed"
};
@SerializedName("where")
Where where;
}
class Where {
@SerializedName("user_id")
Integer userId;
}
}
在 Java 中是否有更好的方法来执行此操作,以及如何在不使用 GSON 的情况下在 Java 中本地表示此 JSON?
更新
我并不是要一份可以帮助我完成上述工作的库列表,我已经知道它们并且显然正在使用它们。我也不需要知道他们的表现。 我要求更好的实现(如果存在),如果 Java 不提供这样的功能,那也可以是一个可接受的答案。 此外,还有一个在 Java 中本地执行相同操作的示例。
【问题讨论】:
-
您可以使用内置的
JSONObject和JSONArray类,但是您还需要管理错误处理。使用像 gson 这样的序列化库更方便 -
嗨,阿卡什,没错!在 Java 中没有其他更好的方法吗?