wginsberg
wginsberg

Reputation: 185

When should an object be used instead of a json object?

I'm designing a program in java where

  1. A lot of objects are just bags of data and don't really require any non-static methods.

  2. I want to easily save and load objects from the hard drive.

  3. Some instances of objects will need one additional attribute which I might add or take away over time.

  4. If some objects do have an additional attribute then I will still treat them as exactly the same kind of object most of the time.

It seems like a good solution to this would be to store these objects in JSON format at runtime and never actually define a dedicated object for them. Is there any reason that you would not want to do this? i.e. is there any reason it is bad practice to store objects in json format when it is just for convenience?

Upvotes: 4

Views: 2508

Answers (1)

Filip
Filip

Reputation: 1068

If you are coming from a Objective-C / PHP (or some other language) dictionaries, or other kind of map, with key/value pairs are common.

But in Java, typically, strong typed object are preferred : sometimes referred as POJOs (Plain Old Java Objects). Java is an Object Oriented language, and you get benefits from OO concepts down the line. Not always obvious for very small applications, but usually it's the way to go. Strong typed object involves a bit more boiler plate code, but any modern IDE will do it for you (generate getters/ setters). So this is no argument against it.

On top of it, it is VERY EASY to store POJO object from/to JSON, using Jackson / GSon / Moxy. There are many good JSON providers / libraries that work with POJO without any config (or very few).

Other advantages I can see off hand :

  • When using pojo IDE will also shows you availables getters / setters while coding.

  • Today you can store your "objects" in JSON on disk, tomorrow you might store them in a database. You can switch from Jackon serialization (or your preferred JSON library) to JPA easily, with a few set of annotations.

  • Many frameworks (JAX-RS, JPA, JAXB) expects strong typed object, and will use reflections or similar methods to inspect and handle your objects.

Upvotes: 1

Related Questions