Reputation: 22183
I'm using the GSON library to parse a message in this way:
Message m = new Gson().fromJson(message, Message.class);
Now I need to parse another message with a complete different form. Message is:
{foo: "aaa", bar: "bbb" }
while the new format is:
{tag1: "ccc", tag2: "ddd"}
How can I distinguish the two formats?
Upvotes: 1
Views: 356
Reputation: 691805
Create a Message
class with 4 fields: foo
, bar
, tag1
and tag2
.
If foo
and bar
are null, then you got the second kind of message. If tag1
and tag2
are null, then you got the first kind of message.
Upvotes: 1
Reputation: 2062
The thing what are you asking is that GSon/Jackson is not designed this way. You are using ObjectMapping API that allows you to convert json into pre-defined class.
In case of your example:
Message m = new Gson().fromJson(message, Message.class);
Message
should always have String foo
and String bar
for mapping actions.
If you know that you have only two string values but always with different fields, please put you attention on Jackson Streaming API
and create universal flexible jsonParser that always have 2 String values. While parsing, you will manually set it to appropriate fields.
Upvotes: 0