dimanche 19 avril 2020

convert java object to json using gson

I am using Java Reflection API to get the objects since I don't know the type of the Object explicitly and I don't have the access to the Classes as well.

if (object != null) {
    HashMap<String, Object> requestDetails = new HashMap<>();
    for (Field field : object.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Object value = null;
        try {
            value = field.get(object);
        } catch (IllegalAccessException e) {
            log.error("Could not found the class", e);
        }
        if (value != null) {
            requestDetails.put(field.getName(), value);
        }
    }
    return requestDetails;
}
return object;

Then I wanted to convert it to the JSON Object using Gson.

for (Map.Entry<String, Object> authzRequestDetail : authzRequestDetails.entrySet()) {
    final Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(getStaticTypeAdapterFactory())
            .create();
    JsonElement element = gson.toJsonTree(authzRequestDetail.getValue());
    valueObject.add(authzRequestDetail.getKey(), element);
}
return valueObject;

Since I don't know the type of the class I am getting the error,

Attempted to serialize java.lang.Class: org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint. Forgot to register a type adapter?

Is it possible to convert it to JSON object without knowing the Class of it, Because I don't have the access to the Classes to Downcast and pass it like,(say the Class is accessible ClassA)

JsonElement element = gson.toJsonTree((ClassA)authzRequestDetail.getValue(),ClassA.class);

please note that this objects contain multiple types.





Aucun commentaire:

Enregistrer un commentaire