troubleshooting Question

How to use Gson for mixed types?

Avatar of burtonrhodes
burtonrhodes asked on
Java
4 Comments1 Solution5181 ViewsLast Modified:
I am trying to figure out how to parse a json string via Gson.  I have a json string (examples below) that can return mixed types into an EmailSubscriber object.  The "merges" field can have just a {string:string, string:string} pattern, OR in certain cases, one of the "strings" is actually a Grouping object.  I have included the two very simplified examples below.  

How can I tell the gson parser to handle the possibility of this extra array object?

Example parsing classes
class EmailSubscriber {
	String status;
                // How can this handle mixed types??
	HashMap<String, String> merges;
                // Getters & setters below...
}
class Grouping {
	String id;
	String name;
	String groups;
	// Getters and setters below...	
}

Example Json reponses
// Works
json: {"status":"subscribed","merges":{"EMAIL":"test@gmail.com","FNAME":"Burton","LNAME":"Rhodes","DROPDWN":"Eggs"}}

// Doesn't work with introduced sub array (grouping)
json: {"status":"subscribed","merges":{"EMAIL":"test@gmail.com","FNAME":"Burton","LNAME":"Rhodes","DROPDWN":"Eggs","GROUPINGS":[{"id":4809,"name":"MyGrouping","groups":"Group1, Group2"}]}}

Example parsing code
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(responseBody).getAsJsonObject();
EmailSubscriber emailSubscriber = gson.fromJson(jsonObject, EmailSubscriber.class);

I tried changing merges to "HashMap<String, Object> merges", but json gives me a the error "com.google.gson.JsonParseException: Type information is unavailable, and the target is not a primitive: [{"id":4809,"name":"MyGrouping","groups":"Group1, Group2"}]"

I am at a loss in how to program the json parser to successfully deserialize this type of "variable" json feed.  Any suggestions?
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros