1

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?

8
  • Create another class, that matches with the structure of the other message. Commented Dec 28, 2015 at 13:54
  • Yes of course, but I don't know if I'm parsing Message1 or Message2, so how can I decide if I need Message1.class or Message2.class??? Commented Dec 28, 2015 at 13:55
  • Ah. If they are radically different things, then you SHOULD know what you're parsing, or there is a design problem somewhere. If they're variations of the same thing, then add the tag1 and tag2 attributes to Message.java, and absent fields will be null in the parsed Message object. Commented Dec 28, 2015 at 13:56
  • I can't contol json schema and the messages are delivered on the same channel. Commented Dec 28, 2015 at 13:57
  • What do you mean by "I can't control json schema"? Do you mean that the received JSON could be anything? If so, wat's the point of parsing it? The fact that they're sent on the same channel doesn't mean you can't know what to expect. The protocol might be: I send two instances of Message, then three instance of OtherMessage. Could you provide a higher-level explanation of what you're trying to achieve? Commented Dec 28, 2015 at 14:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.