我正在开发一个 RESTful Android 移动客户端。我的应用程序和服务器之间的信息交换采用 JSON 格式。所以我现在有点困惑选择什么数据结构来表示 JSON 响应和数据,因为它们有很多。我刚刚停止使用 LinkedHashMap<>,但据我所知,JSON 是无序的。在 Internet 上,我看到人们为此使用 Map<> 或 HashMap<>。
那么问题来了 - 用于此目的的最佳数据结构是什么?或者,如果没有一个明确的答案 - 使用我提到的数据结构的利弊。
最佳答案
我不同意第一个答案。开发 REST 范式是为了让您可以操作对象,而不是操作。
对我来说,最明智的方法是在客户端声明 bean 并解析 json 响应并通过它们请求。我建议使用 GSON library用于序列化/反序列化。 JsonObject
/JsonArray
几乎从来都不是最佳选择。
也许如果您举例说明您将要使用的操作,我们也许能够提供更准确的帮助。
编辑: 让我再举几个 GSON 示例。让我们使用这个线程来比较不同的库。
在大多数情况下,REST 服务与对象进行通信。假设您发布了一个产品帖子,其中引用了商店。
{ "name": "Bread",
"price": 0.78,
"produced": "08-12-2012 14:34",
"shop": {
"name": "neighbourhood bakery"
}
}
然后,如果您声明以下 bean:
public class Product {
private String name;
private double price;
private Date produced;
private Shop shop;
// Optional Getters and setters. GSON uses reflection, it doesn't need them
// However, better declare them so that you can access the fields
}
public class Shop {
private String name;
// Optional Getters and setters. GSON uses reflection, it doesn't need them
// However, better declare them so that you can access the fields
}
您可以使用以下方式反序列化 json:
String jsonString; // initialized as you can
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm"); // setting custom date format
Gson gson = gsonBuilder.create();
Product product = gson.fromJson(jsonString, Product.class);
// Do whatever you want with the object it has its fields loaded from the json
另一方面,您可以更轻松地序列化为 json:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm"); // setting custom date format
Gson gson = gsonBuilder.create();
String jsonString = gson.toJson(product);
关于java - 最适合表示 JSON 的 Java 数据结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866039/