1

I'm interested in converting a JSONObject to a java bean. Let's say I have the following example code:

public class Data {
    String name;
    String email;
    String age;
    String favoriteHobby;
}

JSONObject response = {'name' : 'alex', 'email' : 'alex@alex.com' : 'age' : '22'};
Gson gson = new Gson();
String json = response.toString();
Data data = gson.fromJson(json, Data.class);

This works fine except it doesn't do exactly what I want it to do. The following bit of code would set everything to whatever was in the JSONObject, but it would set favoriteHobby = null.

This doesn't represent the code I'm using in my program, but basically two parameters of my class get initialized to something before I use the fromJson code and are not present in the JSONObject like in the example above. I don't want those two parameters to be overwritten to null by the fromJson() method. I also don't want to have to call every members setters in order to initialize the bean.

Is there anything similar to the fromJson() method, but is a bit more flexible? Does anyone have suggestions on how to accomplish this?

Thank you.

Alex Cauthen
  • 497
  • 5
  • 12
  • 32
  • 1
    Your JSON does not contain `favoriteHobby`, so it will be null... I don't understand the problem or solution you are asking for – OneCricketeer Jun 10 '16 at 16:56
  • Maybe this will help you http://stackoverflow.com/questions/9483348/gson-treat-null-as-empty-string – A. Steenbergen Jun 10 '16 at 16:57
  • I want some method or function that will not overwrite every aspect of the bean if certain member variables are not present in the JSONObject. fromJson() is not the answer, but I'm looking for something that does something similar. Obviously I can accomplish this using setters, but I don't particularly want to do that. I want something a little more robust. Does that make more sense? – Alex Cauthen Jun 10 '16 at 17:22

0 Answers0