我正在开发一个RESTful Android移动客户端,我的应用程序和服务器之间的信息交换是通过JSON进行的。因此,我现在有点困惑要选择哪种数据结构来表示JSON响应和数据,因为有很多选择。我只是选择了LinkedHashMap<>,但据我所知,JSON是无序的。在互联网上,我看到人们使用Map<>或HashMap<>来处理这个问题。所以问题是 - 什么是最好的数据结构来处理这个目的?如果没有明确的答案,那么使用我提到的数据结构的优缺点是什么?
JsonObject
/ JsonArray
几乎从未是最佳选择。{ "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
}
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
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm"); // setting custom date format
Gson gson = gsonBuilder.create();
String jsonString = gson.toJson(product);
import org.json.JSONArray;
import org.json.JSONObject;
我使用这些工具,读取了来自POST请求的JSON数组并将其结果信息存储在我的项目中的类对象中。
对于JSONArray中的每个项,您可以像这样提取JSONObject和属性:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
jsonObject.getString("text");
}
就数据的实际存储而言,如上所述,JSON数据可能因来源不同而采用各种格式,因此通常在客户端进行解析,并保存在应用程序类对象中供使用。或者更通用地,您可以使用Map<String, Object>
来存储数据。
https://dzone.com/articles/which-is-the-right-java-abstraction-for-json
总结:有三种抽象类型:pojos(简单的Java对象)、maps(映射)和lists(列表),以及用于表示对象、数组和基本类型的自定义类。每种类型都有优缺点,没有明显的胜者。XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("myAlias", MyClass.class); // requires a no argument constructor
System.out.println(xstream.toXML(product));
好的,评论区的先生想要一个反序列化的例子,这里给您:
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.alias("myAlias", MyClass.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());
如果您需要进一步的帮助,请告诉我...
Xml
?JsonHierarchicalStreamDriver
是什么?还有哪些模式? - Boris Strandjev如果你不是在进行最简单的映射操作,那么你应该使用完整的类结构。按照 JSON 数据结构创建你的类层次结构,并使用Jackson将 JSON 直接映射到类层次结构中,使用 ObjectMapper。
通过这种解决方案,你不需要将 Object 强制转换为 Map,也不需要使用 JSONObject 或 JSONArray 进行操作,也不需要在代码中进行多级 Map 遍历。你只需将 JSON 字符串传递给 ObjectMapper,然后获取一个包含子对象(甚至集合)的 Object,ObjectMapper 会自动映射它们。
Map<String, Object>
的JSON库。Object
值可以是自动装箱的原始类型之一,列表或另一个映射。虽然不一定是最容易处理的数据结构 - 我强烈建议使用POJO构建真正的对象模型。 - Perception