I am building a JSON-RPC over UDP socket API in Java. There are 6 objects that will be transmitted in JSON:

  • jsonRequest

  • jsonSuccessResponse

  • jsonError

  • jsonErrorResponse

  • jsonNotification

  • jsonSubscription

Under most of these, the following fields would be added to the message and be of types String and Integer:

  • Version

  • Message

  • Result

  • Data

  • Params

  • ID

Ideally, these would all be parsed and generated within the same class file, Json.class

What I normally do in other languages would be to use a struct for each one. In Java, I learned that the guidelines permit using a subclass with instance variables in place of Java's absence of structs. Another way I have thought of would be to use many getter and setter methods.

Unfortunately, the project I am contributing to does not allow sub classes to be used in place of structs. Also, I would prefer not to bloat the class file with too many getter/setter methods.

As I'm just learning Java, I do not know what the most efficient way of doing this is under my circumstances.

My question: is there another way of achieving this without getters/setters, sub classes, and separate class files?

  • What's "Message" vs "Data"? "Result" vs "Data"? "Params"? Subclassing has nothing to do with presence/absence of structs (which in many cases are just another name for "class"). Your list of objects maybe has things that should be subclassed, but some of them look like they should actually be properties of one of the others. How far "up" the stack are you exposing the API - in most cases, I would prefer to not expose any RPC correlation ID, and let my library/framework handle that transparently. – Clockwork-Muse Apr 13 at 0:17
  • jsonSubscription? Are you not following the JSON-RPC specification? jsonrpc.org/specification – whatsisname Apr 13 at 4:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.