简体   繁体   中英

Parse JSON without knowing format (can be one of two different objects)

I have two concrete objects with a known schema (totally different). Then I get JSON from a client and want to map it into one of this object.

Is it possible to somehow check type before conversion, or I have to try to convert it into each of object and check if parsing was correct?

EDIT: In example:

{"id":"1","name":"oneone"}

and second

{"age":50,"type":"elephant"}

Personally, I would parse the JSON using GSON or something similar and look for the key that is unique to one of the JSON formats, for instance "age". In reality, you could probably do this as a String as @user743414 mentioned as well.

UPDATE:

Here is some code to reflect what I'm talking about

JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
Set<String> keys = jsonObject.keySet();
if(keys.contains("age")){
    //Map to one object
} else {
    //Map to the other object
}

If you are sure schema is constant for both JSON's, then simply take a unique parameter like age in this example and check if it exists in the JSON.

If (String.contains(“age”)) {
  //then it’s 2nd JSON
} else {
  //then it’s 1st JSON
}

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