简体   繁体   中英

Define POJO for changing JSON responses

I am using Java 8/Spring 5 to call a third-party API. I am using HttpClient which works well, and I have a POJO that works 99% of the time.

When I call this one service, the JSON looks like:

{"field1":"a",
 "field2":"b",
 "field3:"c"}

Based on different parameters it could come back as:

{"field1":"a",
 "field2":{
    "subfield1:"x",
    "subfield2:"y",
    "subfield3":"z"},
 "field3:"c"}

I am using the latest FastJacksonMapper to convert from JSON string to a Java POJO, and it works in the first instance, but not in the second instance.

I know it may be common for JSON to change based on requests, but I expect JSON to be a little more consistent.

Any thoughts on how I could tweak my POJO? Any JSON annotations I can use to fix this? Or, maybe create a separate POJO so that in case one fails, the other picks up?

Thanks!

So for the same URL and http method you can get different payloads? The same key "field2" might have a string value in option A and a different object in option B? IMHO that's bad design of API.

That third-party API having any description like swagger? Such description will help you generate correct POJO with proper annotations.

If such documentation is not available try to use generators like: http://www.jsonschema2pojo.org/

private static Either<Type1Obj, Type2Obj> getPojoFromJson(String json) {
        try {
            // Type1Obj from json
            return Either.left(obj1);
        } catch (IOException e) {
            try {
                //Type2Obj from json
                return Either.right(obj2);
            } catch (IOException e1) {
                //fallback
            }
            e.printStackTrace();
        }

        return null;
}

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