简体   繁体   English

什么是最适合表示JSON的Java数据结构?

[英]What is the most suitable Java data structure for representing JSON?

I' m developing a RESTful Android mobile client. 我正在开发RESTful Android移动客户端。 Information exchange between my app and server is in JSON. 我的应用程序和服务器之间的信息交换是使用JSON。 So I' m now a little bit confused what data structure choose for represent JSON responses and data because there a lot of them. 因此,我现在有点困惑,选择哪种数据结构代表JSON响应和数据,因为它们很多。 I've just stopped with LinkedHashMap<> but as far as i know JSON is unordered. 我刚刚停止使用LinkedHashMap <>,但据我所知,JSON是无序的。 Across the Internet I saw people use Map<> or HashMap<> for this. 在整个互联网上,我看到人们为此使用Map <>或HashMap <>。

So the question - what is the best data structure for this purpose? 那么问题来了-为此目的最好的数据结构是什么? Or if there is no a univocal answer - pros and cons of using data structures I' ve mentioned. 或者,如果没有明确的答案-使用我提到的数据结构的利弊。

I would disagree with the first answer. 我不同意第一个答案。 The REST paradigm was developed so that you would operate with objects, rather than operations. 开发REST范例是为了使您可以使用对象而不是操作。

For me the most sensible approach will be if you declare beans on the client side and parse the json responses and request through them. 对我来说,最明智的方法是在客户端声明bean并解析json响应并通过它们进行请求。 I would recommend using the GSON library for the serialization/ deserialization. 我建议使用GSON库进行序列化/反序列化。 JsonObject / JsonArray is almost never the best choice. JsonObject / JsonArray几乎从来不是最佳选择。

Maybe if you give examples of the operations you are about to use we might be able to help more precisely. 也许如果您给出了将要使用的操作的示例,我们也许可以提供更精确的帮助。

EDIT: Let me also give a few GSON Examples. 编辑:让我也给出一些GSON示例。 Let's use this thread to compare the different libraries. 让我们使用该线程来比较不同的库。

In the most cases REST services communicate objects. 在大多数情况下,REST服务会通信对象。 Let's assume you make a post of product, which has reference to shop. 假设您发布了一个与商店有关的产品信息。

{ "name": "Bread",
  "price": 0.78,
  "produced": "08-12-2012 14:34",
  "shop": {
     "name": "neighbourhood bakery"
  }
}

Then if you declare the following beans: 然后,如果您声明以下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
}

You can deserialize the json using: 您可以使用以下方法反序列化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

On the other hand you can serialize to json even more easily: 另一方面,您可以更轻松地序列化为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);

Are you talking about receiving and parsing the JSON string from a server request? 您是在谈论从服务器请求中接收和解析JSON字符串吗?

For that you can use: 为此,您可以使用:

import org.json.JSONArray;
import org.json.JSONObject;

Using these, I read through my JSON array from my POST request and store the resulting information in Class objects in my project. 使用这些,我从POST请求中读取了JSON数组,并将结果信息存储在项目的Class对象中。

For each item in JSONArray, you can extract the JSONObject and attributes like this: 对于JSONArray中的每个项目,都可以像这样提取JSONObject和属性:

for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    jsonObject.getString("text");
}

As far as actually storing the data, like mentioned above, JSON data can come in a wide array of formats depending on the source, and as such, it is usually parsed on the client end and saved in your application Class objects for use. 就实际存储数据而言,如上所述,JSON数据可以有多种格式,具体取决于源,因此,通常在客户端将其解析并保存在应用程序Class对象中以供使用。 Or more generically, you could store the data using Map<String, Object> 或更笼统地说,您可以使用Map<String, Object>存储数据

If you are doing anything other than the most simple mapping then you should use a full class structure. 如果除了最简单的映射外,您还需要执行其他操作,则应使用完整的类结构。 Create your class hierarchy as a mirror of the data structure in JSON and use Jackson to map the JSON directly to the class hierarchy using the ObjectMapper. 创建类层次结构作为JSON中数据结构的镜像,并使用Jackson通过ObjectMapper将JSON直接映射到类层次结构。

With this solution you don't have any casting of Object to Map or messing around with JSONObject or JSONArray and you don't have any multi-level map traversal in your code. 使用此解决方案,您无需强制转换要映射的对象或使用JSONObject或JSONArray进行处理,并且代码中无需进行任何多级映射遍历。 You simply take the JSON string, feed it to the ObjectMapper, and get a your Object, which contains child objects (even collections) automatically mapped by the ObjectMapper. 您只需获取JSON字符串,将其输入到ObjectMapper,然后获取一个Object,该Object包含由ObjectMapper自动映射的子对象(甚至是集合)。

I've used xstream to serialize JSON , in the following way: 我使用xstream通过以下方式序列化JSON

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));     

Ok, the gentleman in the comments wants a deserialization example, here you are: 好的,评论中的绅士想要反序列化示例,您在这里:

XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.alias("myAlias", MyClass.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());

Let me know if you need further assistance... 让我知道您是否需要进一步的帮助...

This is easily the best answer I've seen: 这是我见过的最好的答案:

https://dzone.com/articles/which-is-the-right-java-abstraction-for-json https://dzone.com/articles/which-is-the-right-java-abstraction-for-json

Summary: there are three abstrations: pojos, maps and lists, and custom classes to represent objects, arrays, and primitives. 简介:有三种摘要:pojos,映射和列表,以及代表对象,数组和基元的自定义类。 There are advantages and disadvantages to each, with no clear winner. 每个都有优缺点,没有明确的赢家。

Pojos have the biggest advantages, but you can't always use them. Pojos具有最大的优势,但您不能总是使用它们。 Use them if you can, and use the others if you must. 如果可以,请使用它们;如果需要,请使用其他。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM