简体   繁体   中英

Parse multiple types of json with GSON

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM