Java Utililty Methods Object to Json

List of utility methods to do Object to Json

Description

The list of methods to do Object to Json are organized into topic(s).

Method

Stringobj2Json(Object obj)
obj Json
try {
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
    return ow.writeValueAsString(obj);
} catch (Exception e) {
    e.printStackTrace();
    return null;
Stringobject2Jason(Object obj)
object Jason
try {
    return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
    return null;
booleanobjectToString(StringBuilder bld, ObjectNode node, int depth, boolean newLine)
object To String
if (newLine) {
    indent(bld, depth);
    newLine = false;
if (node.size() > 0) {
    bld.append("{\n");
    newLine = true;
boolean first = true;
for (Iterator<Map.Entry<String, JsonNode>> itr = node.fields(); itr.hasNext();) {
    if (first) {
        first = false;
    } else {
        if (newLine) {
            indent(bld, depth);
            newLine = false;
        bld.append(',');
        bld.append('\n');
        newLine = true;
    Map.Entry<String, JsonNode> entry = itr.next();
    indent(bld, depth);
    bld.append('\"');
    bld.append(entry.getKey());
    bld.append('\"');
    bld.append(':');
    newLine = toString(bld, entry.getValue(), depth + 1, false);
    if (newLine) {
        indent(bld, depth);
        newLine = false;
if (node.size() > 0) {
    bld.append('\n');
    newLine = true;
if (newLine) {
    indent(bld, depth);
    newLine = false;
bld.append('}');
return false;
JsonNodeobjToJson(Object obj)
Converts a generic Java object to a JsoNode object
return mapper.valueToTree(obj);
StringtoJson(List list)
to Json
try {
    return new ObjectMapper().writeValueAsString(list);
} catch (JsonProcessingException e) {
    e.printStackTrace();
return "";
StringtoJson(Object dto)
to Json
ObjectMapper mapper = createObjectMapper();
return mapper.writeValueAsString(dto);
StringtoJson(Object message)
to Json
return mapper.writeValueAsString(message);
StringtoJson(Object o)
to Json
try {
    return getObjectMapper().writeValueAsString(o);
} catch (Exception e) {
    e.printStackTrace();
    return "<exception>";
StringtoJson(Object o)
to Json
return JSON_MAPPER.writeValueAsString(o);
StringtoJSON(Object obj)
to JSON
try {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
    e.printStackTrace();
    return "{error: " + e.getMessage() + "}";
...