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

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>

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.

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

Related

Create some hash type structure in Gson to access values in json instead of creating custom classes

If I have a json object inside a bigger json:
customer_data: {
details: {
personal_info: {
first: “George”
last: “Washington”
}
order_details: {
canceled: “true”
id:”1234”
}
}
If I want only specific values of customer_data besides traversing the structure using getAsJsonObject etc is there any other way to access them if I would like to avoid creating a CustomerData class since I won’t need to access all the data of customer_data?
Note: I am using Gson
Gson don't supports data access via XPath anology, and if you don't want to use Data Binding, you have only two ways: Tree Model or Streaming API.
The simpliest will be Tree Model:
JsonObject customerData = someBiggerJson.get("customer_data").getAsJsonObject();
String someInfo = customerData.get("some_field").gatAsString();
...
In case of using Streaming API you should iterate in your json to field you need by your hands.
reader = new JsonReader((<input_stream>)
reader.nextString()
reader.beginObject()
reader.endObject() etc..

Serialize vertx JsonObject using Jackson

I'm using vertx and Jackson in my development. In one of my classes, I got a field of type JsonObject, something like this:
class User
private String name;
private JsonObject details;
This details field can contain other JsonObjects or JsonArrays, e.g.:
{"details": [{"street": "Broadway"}, {"building": 20}]}
I don't have a dedicated class of this structure, as far as there's no fixed structure and it can vary.
details object is being created in the way like this:
JsonObject details = new JsonObject().put("name", "value").put("another", "another")
This aproach allows me to store details of any structure inside my code. As far as I don't need to manipulate this data on my backend, I don't want to create a special structure for it.
Everything works fine until I'm trying to serialize this JsonObject using Jackson. Unfortunately, instead of beatiful JSON string, Jackson gives me map object serialized with all map's additional fields.
How can I serialize JsonObject of vertx using Jackson?
Looking at JsonObject's javadoc , I saw a getMap() method. I know Jackson is capable of serializing Maps with ease.
Finally, it turned out that vertx already has it's own implementation of Serializer.
It's enough just to use theirs class to perform serialization (which will use Jackson undercover).
JsonObject user = new JsonObject(Json.encode(new User());
And it works fine.
I would suggest creating using https://static.javadoc.io/com.fasterxml.jackson.core/jackson-databind/2.7.3/com/fasterxml/jackson/databind/ObjectMapper.html#convertValue(java.lang.Object,%20java.lang.Class) like this:
new JsonObject((Map)Json.mapper.convertValue(new User(), Map.class));
Converting to and from String takes time.

Get JSONobjects from string

So i have a string which contains multiple JSONobjects and looks like this:
[{"one":"1","two":"2","three":"3"},
{"one":"4","two":"5","three":"6"},
{"one":"7","two":"8","three":"9"}]
How can i iterate through this string using java and get every object? Is it possible using JSON api, or i should make parser by myself?
GSON library is a good option to convert java object to json string and vise versa.
for converting json to java object use: fromJson(String, Class)
for converting java object to json string use: toJson(Object)
In your case it's a List of Object.
sample code:
class MyPOJO {
private String one;
private String two;
private String three;
// getter & setter
}
String jsonString = "[{\"one\":\"1\",\"two\":\"2\",\"three\":\"3\"}, {\"one\":\"4\",\"two\":\"5\",\"three\":\"6\"}, {\"one\":\"7\",\"two\":\"8\",\"three\":\"9\"}]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(jsonString, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
Note: The name of variable in your java POJO class should be same as JSON string.
Find more examples...
You Should defiantly use the Json API, you can download the jar from here and simply use
JSONArray myArray = new JSONArray(yourString);
for (int i=0; i < myArray.length(); i++)
{
JSONObject currentOb = myArray.get(i);
doSomthing(currentOb);
}
It is obvious that you should use a JSON library. Existing libraries are tested and validated. In very rare conditions you may need to write your own parser, your own implementation. If that is the case, I think you should double check your design. Because you might be doing something wrong if the existing library is in conflict with your design.
Library selection depends on your environment and your performance requirements.
In my case, Spring3 is the environment and the JSON objects are huge (10-20MB), and inserts occur on existing JSON objects. We prefer Jackson. Jackson's performance is outstanding. An independent performance comparison is in here. You will see that the Jackson outperforms GSon in here.

Creating json object from POJO object in restful web service

I am developing a web application. I have database used by the web service. I want to send the same data to the web pages which are calling web service.
I get the data i.e. single row from the database by using hibernate and POJO classes(getColumn). Now I have object(POJO class) of the Table which represent single row of the database. For sending it back to the web pages (html, jsp), I need to convert it to the json object as my web service returns the json object.
How can I make Json object from POJO classes. There are many other ways to generate Json String but i want json object.
How can do this?
Thank you
You can use GSon to convert json object to java object
Link
to refer example.
Gson gson = new Gson();
//to get json object use toJson
String json = gson.toJson(obj);
//to get java object use fromJson
MyClass obj = gson.fromJson(jsonObj, MyClass.class);
or
jackson is also pretty fast and easy to use
private ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.convertValue(YOUR POJO CLASS, JsonNode.class);
You can use Jackson and achieve this as above. GSON also does the job.
The way I use is with Google's Gson library. Very simple and powerful
Spring and Jackson as it is so simple. You can find a very basic example below Jackson/spring JSON example

JSON Polymorphism

I have a List of javascript objects on my client side, which are a list of "events" that a user has executed. When the user is ready, I want to send this to the server. The order of events is important, so preserving the list order is necessary.
What I would like to do is to have a JSON library (don't mind which one) to bind the JSON to some Event objects in my Java code, where Event is an abstract class, and I have 3 concrete classes that all extend Event (lets say EventA, EventB and EventC).
Ideal scenario would be something like
List<Event> events = jsonlibrary.deserialise(jsonString);
which may contain a list of items such as
[eventA, eventC, eventA, eventA, eventB]
Is this possible, or do I have to inspect the JSON tree manually, and deserialise the individual elements of the json array?
JSON objects are just key/value pairs and contain no type information. That means identifying the type of a JSON object automatically isn't possible. You have to implement some logic on the server-side to find out what kind of event you are dealing with.
I would suggest to use a factory method which takes a json string, parses it to find out what kind of Event it is, builds an Event object of the correct subclass and returns it.
You could use Genson library http://code.google.com/p/genson/.
It can deserialize to concrete types if the json was produced using Genson. Otherwise you only need to add something like [{"#class":"my.java.class", "the rest of the properties"}...]
// an example
abstract class Event {
String id;
}
class Click extends Event {
double x, y;
}
// you can define aliases instead of plain class name with package (its a bit nicer and more secure)
Genson genson = new Genson.Builder().setWithClassMetadata(true).addAlias("click",
Click.class).create();
String json = "[{\"#class\":\"click\", \"id\":\"here\", \"x\":1,\"y\":2}]";
// deserialize to an unknown type with a cast warning
List<Event> events = genson.deserialize(json, List.class);
// or better define to which generic type
GenericType<List<Event>> eventListType = new GenericType<List<Event>>() {};
events = genson.deserialize(json, eventListType);
EDIT
here is the wiki example http://code.google.com/p/genson/wiki/GettingStarted#Interface/Abstract_classes_support
Why not using jackson json library ?
It is a full Object/JSON Mapper with data binding functionnality.
It is fast, small footprint, documented, overused, and many others things you will enjoy!
I began a library that implements the desired fonctionality (for json and xml) if the json is encoded by the same library :
https://github.com/giraudsa/serialisation
to use it,
MyObject myObject = new SpecialisedObject();
String json = JsonMarshaller.ToJson(myObject);
MyObject myClonedObject = JsonUnMarshaller(json);

Categories

Resources