0

Let's say I have a JSONObject like this example :

{ "name":"John", 
"age":30, 
"car":null,
contact":  {
      "telephone": "12345", 
      "extension": "34
    }
 }

and I would like to create a class in which I would write some methods to get certain values from JSONObjects with this format.

My first thought was to create a class (let's call it "Person") which extends JSONObject and add the methods I need, the problem is that I get the JSONObject as the return object of a method in a REST api, not from a JSONObject's class constructor, so I cannot create a constructor in Person using it's parent constructor nor cast that JSONObject to Person as I would have ClassCastException. What do you think is the best/proper way to approach this? What am I missing?

Another option would be creating Person class (no extends) with a JSONObject as a class variable and create a constructor with JSONObject as the only parameter. But that's seems not much "elegant" to me.

That's one of those issues that make me think I probably don't understand enough OOP yet as I have the impression there's an obvious way to get it done I can't see now haha

Thanks in advance!

jordileft
  • 39
  • 6
  • 1
    Don't use JSONObject at all. Use a tool like Jackson to map to POJOs. – Michael Mar 07 '19 at 16:42
  • What @Michael said. Also the answer to "_is extends the right approach_" is usually no. – Boris the Spider Mar 07 '19 at 16:43
  • 1
    `Another option would be creating Person class (no extends) with a JSONObject as a class variable and create a constructor with JSONObject as the only parameter.` This is the correct approach. You are trying to link two very different platforms. Hence, you need individual representations of the objects in question. – Susmit Agrawal Mar 07 '19 at 16:47
  • Thanks @Michael , never heard about it but looks like a pretty straight and easy tool. – jordileft Mar 07 '19 at 18:10
  • @BoristheSpider , I solved that particular case as Michael said, but beside that I would like to know how should I approach a problem like this with any other class. So the question would be, I've got a parent class and a subclass and I'm only able to get an instance of the parent class via a get method, how can I convert it to my subclass? Is the solution that Susmit pointed the best? – jordileft Mar 13 '19 at 20:05
  • Subclass _is a_ parent - so the question is why would you ever need to convert? Do you often find yourself needing to convert a `List` to an `ArrayList`? No! Because the abstraction provided gives you the functionality you need. If you cannot comply with Liskov then you have broken inheritance. TL;DR: your premise is wrong. – Boris the Spider Mar 14 '19 at 05:07
  • Thanks @BoristheSpider , I'll explain better the reason in a new topic as comment hasn't enough characters for a full explanation. https://stackoverflow.com/questions/55160608/extend-a-class-who-has-no-constructor – jordileft Mar 14 '19 at 10:50

0 Answers0