mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2026-01-11 14:57:08 +00:00
56 lines
1.6 KiB
Plaintext
56 lines
1.6 KiB
Plaintext
package {{invokerPackage}};
|
|
|
|
import com.fasterxml.jackson.annotation.*;
|
|
import com.fasterxml.jackson.databind.*;
|
|
import com.fasterxml.jackson.datatype.joda.*;
|
|
|
|
import java.io.IOException;
|
|
|
|
{{>generatedAnnotation}}
|
|
public class JSON {
|
|
private ObjectMapper mapper;
|
|
|
|
public JSON() {
|
|
mapper = new ObjectMapper();
|
|
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
|
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
|
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
|
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
|
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
|
mapper.registerModule(new JodaModule());
|
|
}
|
|
|
|
/**
|
|
* Serialize the given Java object into JSON string.
|
|
*/
|
|
public String serialize(Object obj) throws ApiException {
|
|
try {
|
|
if (obj != null)
|
|
return mapper.writeValueAsString(obj);
|
|
else
|
|
return null;
|
|
} catch (Exception e) {
|
|
throw new ApiException(400, e.getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Deserialize the given JSON string to Java object.
|
|
*
|
|
* @param body The JSON string
|
|
* @param returnType The type to deserialize inot
|
|
* @return The deserialized Java object
|
|
*/
|
|
public <T> T deserialize(String body, TypeRef returnType) throws ApiException {
|
|
JavaType javaType = mapper.constructType(returnType.getType());
|
|
try {
|
|
return mapper.readValue(body, javaType);
|
|
} catch (IOException e) {
|
|
if (returnType.getType().equals(String.class))
|
|
return (T) body;
|
|
else
|
|
throw new ApiException(500, e.getMessage(), null, body);
|
|
}
|
|
}
|
|
}
|