Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read and write Json properties using methods (ie. getters & setters) #232

Open
GoogleCodeExporter opened this issue Mar 19, 2015 · 33 comments

Comments

@GoogleCodeExporter
Copy link

if your object has an int getId(); method. Maybe you want to have a 

@Field("id")
public int getId();

When the Json is generated the getId() method is called and the result is 
placed in "id"
I know that I could have a int field in my class, but, in my case the Id is 
generate by Hibernate once the object is saved.

Original issue reported on code.google.com by Germanattanasio on 7 Sep 2010 at 2:04

@jansohn
Copy link

jansohn commented Dec 9, 2015

This would be very helpful when working with JavaFX properties, e.g. javafx.beans.property.StringProperty, as these properties cannot be instantiated with an empty constructor.

@schlm3
Copy link

schlm3 commented Apr 13, 2016

GSon is useless for me without this feature. Wanted to use it for client server communication together with a GWT app while using a common Data interface. The point is, that the server already has it's very own object model and likes only to provide a view for the json serialisation which should look like the data required inside the GWT app. Would have worked perfectly if gson had supported getter/setter like serialisation.

@rajsrivastav1919
Copy link

I have the same requirement, I want Gson to use setters for setting the field instead of reflection.
I am deserializing a thrift object's json (which does not contain isSet vector details). If setter methods were called, isSet vector will be formed automatically.
(It can be argued that isSet vector should have been present in the json in the first place. Agreed, but it is an internal field for use by thrift and thrift takes the pain of maintaining it every time some fields are edited.)

With current Gson implementation, thrift objects can't be deserialized "effectively". Other JSON & XML deserializing libraries (like Jackson, CastorXML) call setters, and hence the objects formed are compatible with thrift. For now, I am using Gson by making changes in it for calling setter methods instead of using reflection.

From the thread above, I see that you don't want to give native support in Gson for this feature.
My suggestion is to add a flag in GsonBuilder which indicates Gson to use getter/setter methods. This will be set to false by default so the current functionality does not change. If set to true, Gson will try to call getter/setter methods if present, otherwise fallback to reflection for getting/setting the values. This will make Gson compatible to be used for Thrift objects also.

For 99% POJO classes current implementation works I agree. But, having as an optional feature shouldn't harm anyone I guess.

@inder123
Copy link
Collaborator

@rajsrivastav1919 Would be great for someone to fork Gson with support for this. As we understand the solution better, we will consider adding it.

@rajsrivastav1919
Copy link

Thanks @inder123 for the consideration. I will try to point out some genuine use cases for this if I find any.

Meanwhile, here is how I have been using it till now in various projects in my company. If you have some suggestions regarding the approach, I'll be glad to incorporate them.

@tobilarscheid
Copy link

Hi, let me add to this and outline our teams desired use case for this feature:

We came to use gson as the couchdb java driver uses gson. Every POJO you want to store is serialized by gson. What we would like to do is add a generic interface that contains the standard fields (i.e. their getters) that every object in our db needs (Think revision, last updated, stuff like this). Unfortunately this is not possible with gson not being able to serialize based on getter/setter methods.

@erik777
Copy link

erik777 commented Aug 3, 2017

Please make this a priority. I have a case where the base object has a property that subclasses override and do not want to permit incoming data to change. I find it ironic that getters/setters are rendered useless with Gson. These things do not work:

protected final Doctype doctype = Doctype.Reg;

OK with Java. Not OK with Gson:

Caused by: java.lang.IllegalArgumentException: class com.blah.Subclass declares multiple JSON fields named doctype

@Override
public void setDoctype(Doctype doctype) {
	// Ignore
}

Ignored by Gson.

@Override
public Doctype getDoctype() {
	return Doctype.Reg;   // immutable
}

Also ignored by Gson.

There is no elegant work-around to protect the data from overwrite by fromJson. Your only option seems to be to overwrite the property in the client code after executing fromJson. This undoes sacred contracts of OO programming.

HUGE BUMP!

If anyone forks this please come back here and comment. I'd personally be happy with a getter/setter only implementation because the security holes the current Gson introduces is pretty significant in today's rapidly growing JSON based API universe. You have no idea what data is coming in from external consumers of your API, and you have no natural OO way to protect internal data.

@rajsrivastav1919
Copy link

@erik777 Here is an implementation for the same if you want to use getter/setter methods. I've added a flag to tell Gson whether to use getter/setter methods or work in the default way.

Though I agree with @inder123 that ideally Gson should be defaulting to using reflection to set fields. Otherwise, it won't be a pure Gson serialisation/deserialisation library (which it is meant for). An object serialised via Gson should exactly give the same object when deserialised with it, which will not be always true if using getter/setter methods. Hence, only getter/setter implementation is not suitable here. Still, I would appreciate if Gson at least decides to include flag based approach in their code, because in some or other case, its useful.

@james-hu
Copy link

james-hu commented Apr 1, 2018

Is it possible to have @rajsrivastav1919 's implementation into the code base? Besides, it might also be useful if setAccessible(true) code can be opt-out by configuration.

@TheLoneKing
Copy link

I need this feature too. Any updates on this. I see an open pull request but there hasn't been much improvement on that either.

@rajsrivastav1919
Copy link

@TheLoneKing I have not made any updates there because there hasn't been any decision to include it. In case it is decided to approve these changes, I will make the changes as per the latest code at that time.

@mattbushell
Copy link

mattbushell commented Jul 29, 2019

I need this feature; i know i could use a TypeAdapter, but this option would be more succinct

Usecase normalising data I do not control:

public class SomeResponse {
	@SerializedName("SomeObject")
	Map<Integer, SomeObject> idSomeObjectMap;

	public void setIdSomeObjectMap(Map<Integer, SomeObject> idSomeObjectMap) {
		this.idSomeObjectMap = idSomeObjectMap;

		//need to put ids on objects
		idSomeObjectMap.entrySet().stream().forEach(me -> me.getValue().setSomeObjectID(me.getKey()));
	}

	public static class SomeObject {
		Integer someObjectsID;

		@SerializedName("N")
		String someObjectsName;

		public void setSomeObjectID(Integer someObjectID) {
			this.someObjectsID = someObjectID;
		}
	}
}

Response for example:

"SomeObject": {
      "173": {
        "N": "SomeObject has a name"
      },
      "246": {
        "N": "SomeObject also has a name"
      }
}

@onacit
Copy link

onacit commented Jul 25, 2020

Is this still in progress...???

@aakashchauhan71
Copy link

I also require this feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests