-2

Can we declare a attribute of type json object in a java model class

For example.

   public class Sample {
    private JSONobject data;
   //getters and setters
   }

In this way can we declare an attribute? If so, do we need to add anything extra? I got an exception on runtime while populating the field.

janithcooray
  • 188
  • 2
  • 15
SHILPA
  • 57
  • 1
  • 3
  • 11

1 Answers1

0

I've yet seen anyone using JSONObject /JsonObject in a model.

Please refer to this for the difference between POJO (java model object) and DTO (objects like JSONObject) and this for when should you use JSONObject.

So the answer to your question is probably not.

This answer to serialization/deserialization should help you understand POJO and JSON better.

So far, I've only seen primitive values and list in a java model.

The JSONObjects need to be deserialized to POJO objects (vice versa). (Please refer to this post on why use POJO over JSONObject)

Your code won't even compile as it is asking for the parameter type of JSONObject which is not among java primitive values and part of Java collection.

However, you could argue that you can have

public class Sample<JSONobject> {
    private JSONobject data;
    //getters and setters
}

But this would be an unrelated object inside another object, which has no logic in implementation. For best practice, it's better to follow the common usages as many code bases would be serializing/deserializing JSON.