简体   繁体   中英

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

I' m developing a RESTful Android mobile client. Information exchange between my app and server is in 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. I've just stopped with LinkedHashMap<> but as far as i know JSON is unordered. Across the Internet I saw people use Map<> or HashMap<> for this.

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.

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. I would recommend using the GSON library for the serialization/ deserialization. JsonObject / JsonArray is almost never the best choice.

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. Let's use this thread to compare the different libraries.

In the most cases REST services communicate objects. 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:

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:

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:

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?

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.

For each item in JSONArray, you can extract the JSONObject and attributes like this:

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. Or more generically, you could store the data using 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.

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. 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.

I've used xstream to serialize JSON , in the following way:

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

Summary: there are three abstrations: pojos, maps and lists, and custom classes to represent objects, arrays, and primitives. There are advantages and disadvantages to each, with no clear winner.

Pojos have the biggest advantages, but you can't always use them. Use them if you can, and use the others if you must.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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