以下是我想在我的 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 中 native 执行相同操作的示例。
最佳答案
好吧,有几个库可用于将对象序列化和反序列化为 json
。
GSON是最简单的,您可以将您的 POJO
(计划旧的 java 对象)转换为 JSON
而无需注释它们。
LoganSquare是为此目的最好的库,它需要您注释您的字段,但性能相当高。
Github 页面实际上讲述了 LoganSquare 与其他选项的基准研究。
还有一些像Moshi和 Jackson但考虑到平台的限制,我发现 LoganSquare
是最好的。
As far as Native capability is concerned, Java so far does not provide any such utility and if someone is not interested in
Third partylibs
, the project I have mentioned above are all open source objects, one can fork them and implement their own version based on one's usecases.
关于java - 在 Java 中创建 JSON 对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41846293/