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

I am developing a program in java where

  • Lots of objects are just bags of data and don't really require any non-static methods.

  • I want to easily save and load objects from my hard drive.

  • Some object instances will require one additional attribute that I could add or remove over time.

  • If some objects have an additional attribute, I will still treat them as the same kind of object most of the time.

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

+3


source to share


2 answers


  • Lots of objects are just bags of data and don't really require any non-static methods. Will this data be used by multiple classes? Will you change the data? If you answered yes to any of these, I would create an object.

  • I want to easily save and load objects from my hard drive. JSON is a great way to do it, no problem here.

  • Some object instances will need one additional attribute that I can add or subtract over time. JSON is designed to be flexible as such, no problem or reason you need a class / object to do this

  • If some objects have an additional attribute, I will still treat them as exactly the same object type most of the time. Again, there is no JSON issue here.



+1


source


If you are coming from Objective-C / PHP (or some other languages) dictionaries or some other type of map, key / value pairs are generic.

But in Java, a strongly typed object, sometimes called POJO (Plain Old Java Objects), is generally preferred. Java is an object oriented language and you benefit from OO concepts. Not always obvious for very small applications, but it is usually the way to go. A strong typed object includes a little more boilerplate code, but any modern IDE will do it for you (create getters / setters). So this is not an argument against him.

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



Other benefits that I can see:

  • When using Pojo IDE it will also show if there are getters / setters available when coding.

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

  • Many frameworks (JAX-RS, JPA, JAXB) expect a strong typed object and will use reflections or similar methods to validate and process your objects.

0


source







All Articles