NeoWang
NeoWang

Reputation: 18533

Should I define one class for each REST JSON Request and Response?

In my android app, I need to post JSON data to several REST APIs and get JSON data back for parsing. I want to use GSON to serialize/deserialize the data.

Each REST API has different input/output fields, should I define a separate class to hold data for each API request and response like this?

public class API1RequestData{
  public String field1;
  public String field2;
}

I am asking this, because if I am using python to construct the JSON request, I don't need to define classes, a dictionary will do.

Upvotes: 2

Views: 1061

Answers (2)

Fernando Carvalhosa
Fernando Carvalhosa

Reputation: 1107

I believe you should by design (I end up re-using them when I can though). This guarantees you don't send unnecessary data to the server.

If you are really worried about data consumption, i recommend you to:

  • Do not send null values to the server (just check if they arrive null);
  • Use integers for errors in the response, instead of booleanor string
  • Send only new stuff when refreshing some data (save some checksum/timestamp of the "data version" and check it)
  • ...

It all depends on what your application needs. Sometimes it's not worth adding some design patterns that will slow down development in exchange for nothing

Upvotes: 2

Jon Helms
Jon Helms

Reputation: 187

I created a base class that has all of the functions for post and get, then I inherit that class and override the collection part of the class. Part of every request is authentication, request type, and request body. Part of every response is response type, permission level, and the data. The data becomes a collection on most of the inherited classes. This works well for serialization and deserialization on both ends and using the base class keeps code maintenance to a minimum.

I've had other projects where I've done things differently for various reasons. Whatever works is good. If you have identically structured requests but the names are what is different, then just make one class and rely on context to know what it is. If the requests are structured differently, use different classes.

Upvotes: 2

Related Questions