It's my first post in this forum. I have just begun my OO journey. Yesterday I was wondering how to represent JSON structure as object model.
I came up with something like :
Now I am little confused about JsonObject. I am good with "key" part of Map, as it could be only String, but "value" could be anything "String || Number || JsonObject || JsonArray || TRUE || FALSE || NULL"
Is it good to do something like :
I might be thinking loud here, (and I smell some bad things as well). Is it good to inherit new object just for making it same type as of its parent. Please let me know better approach for this model.
I think you're overthinking this. What's the point of doing what you're doing?
When it comes to JSON and Java, the problem is actually simpler than what you have in mind: Take a JSON string and map it to a Java object or conversely, take a Java object and translate it into a JSON string. The assumption here is that you have a specific Java object definition that matches the JSON structure. Maybe I'm missing something but IMO, using a generic data structure that can handle the entire universe of possible JSON strings is just an unnecessary layer of abstraction that only adds complexity and no real value.
And there are pleny of frameworks that allow you to easily map between JSON and Java, like Google Gson, JSON Simple or Jackson. It's even possible to combine some of them with a JAXB implementation, and use JAXB to serialize to, and deserialize from JSON instead of XML. Or is this perhaps purely meant as an exercise to practice some OO concepts?
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Jelle Klap wrote:Or is this perhaps purely meant as an exercise to practice some OO concepts?
If this is your intent, then you probably shouldn't start with a recursive structure like JSON. I suggest you choose something simpler, with not only data but interesting behavior as well. Behavior is really what an object should be about; encapsulated data is secondary and should be relevant to the behavior of the object.
That is, when you start thinking "objects", these are some of the basic questions you want to ask:
1. What interesting things does this object do? (Responsibilities)
2. What information does the object need to do these interesting things? (Data encapsulation)
3. Given enough information, can this object do these things independently or does it need help from other objects? (Collaboration)