Serialize Java Map to create dynamic GraphQL payload string

I am building a REST application in Java that needs to dynamically build GraphQL payloads to send to a GraphQL API.

We will receive a String entityType = "MyEntity" and a Map<String, Object> myMap that might look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"blobUrl": "myurl.com",
"accountId": 12345,
"user": {
"id": 4,
"name": "username"
}
}
</code>
<code>{ "blobUrl": "myurl.com", "accountId": 12345, "user": { "id": 4, "name": "username" } } </code>
{
    "blobUrl": "myurl.com",
    "accountId": 12345,
    "user": {
        "id": 4,
        "name": "username"
    }
}

It could have many other keys with values of different types instead, so there is no way I can create a template beforehand that indicates which variables need to be bound.

All that we know about the GraphQL payload ahead of time, is that it will be of this format:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>mutation {
Create%s(%s)
}
</code>
<code>mutation { Create%s(%s) } </code>
mutation {
    Create%s(%s)
}

With that information, I want to generate the following GraphQL payload:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>mutation {
CreateMyEntity(
blobUrl: "myurl.com"
accountId: 12345
user: {
id: 4
name: "username"
}
)
}
</code>
<code>mutation { CreateMyEntity( blobUrl: "myurl.com" accountId: 12345 user: { id: 4 name: "username" } ) } </code>
mutation {
    CreateMyEntity(
        blobUrl: "myurl.com"
        accountId: 12345
        user: {
            id: 4
            name: "username"
        }
    )
}

There are ways I could do this by manually looping through myMap and building the payload with a StringBuilder, but I want to know if there is a better or pre-existing way of doing this.

I have looked all over and haven’t found anything that doesn’t involve having a template that clearly defines the variables and their types.

2

I believe you are focused on building the query string yourself.

Here is an example of custom serialization:

Entry point

This contains the main method.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package org.example.graphql;
public class Runner {
public static void main(String[] args) throws Exception {
GraphQLSerializer entitySerializer = new GraphQLMutationSerializer("CreateMyEntity");
String payload = entitySerializer.serialize(jsonInput);
System.out.printf("Formatted properly? %b%n", payload.equals(expectedGraphQL));
}
private static final String jsonInput = """
{
"blobUrl": "myurl.com",
"accountId": 12345,
"user": {
"id": 4,
"name": "username"
}
}
""";
private static final String expectedGraphQL = """
mutation {
CreateMyEntity(
blobUrl: "myurl.com"
accountId: 12345
user: {
id: 4
name: "username"
}
)
}
""".trim();
}
</code>
<code>package org.example.graphql; public class Runner { public static void main(String[] args) throws Exception { GraphQLSerializer entitySerializer = new GraphQLMutationSerializer("CreateMyEntity"); String payload = entitySerializer.serialize(jsonInput); System.out.printf("Formatted properly? %b%n", payload.equals(expectedGraphQL)); } private static final String jsonInput = """ { "blobUrl": "myurl.com", "accountId": 12345, "user": { "id": 4, "name": "username" } } """; private static final String expectedGraphQL = """ mutation { CreateMyEntity( blobUrl: "myurl.com" accountId: 12345 user: { id: 4 name: "username" } ) } """.trim(); } </code>
package org.example.graphql;

public class Runner {
    public static void main(String[] args) throws Exception {
        GraphQLSerializer entitySerializer = new GraphQLMutationSerializer("CreateMyEntity");
        String payload = entitySerializer.serialize(jsonInput);

        System.out.printf("Formatted properly? %b%n", payload.equals(expectedGraphQL));
    }

    private static final String jsonInput = """
            {
                "blobUrl": "myurl.com",
                "accountId": 12345,
                "user": {
                    "id": 4,
                    "name": "username"
                }
            }
            """;

    private static final String expectedGraphQL = """
            mutation {
                CreateMyEntity(
                    blobUrl: "myurl.com"
                    accountId: 12345
                    user: {
                        id: 4
                        name: "username"
                    }
                )
            }
            """.trim();
}

Interface

This is an interface for serialization.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package org.example.graphql;
import com.fasterxml.jackson.core.JsonProcessingException;
public interface GraphQLSerializer {
String serialize(String jsonInput) throws JsonProcessingException;
}
</code>
<code>package org.example.graphql; import com.fasterxml.jackson.core.JsonProcessingException; public interface GraphQLSerializer { String serialize(String jsonInput) throws JsonProcessingException; } </code>
package org.example.graphql;

import com.fasterxml.jackson.core.JsonProcessingException;

public interface GraphQLSerializer {
    String serialize(String jsonInput) throws JsonProcessingException;
}

Implementation

Here is where we parse the JSON and format it.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package org.example.graphql;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class GraphQLMutationSerializer implements GraphQLSerializer {
private final ObjectMapper objectMapper = new ObjectMapper();
private final String mutationName;
private final int indentSize;
public GraphQLMutationSerializer(String mutationName, int indentSize) {
this.mutationName = mutationName;
this.indentSize = indentSize;
}
public GraphQLMutationSerializer(String mutationName) {
this(mutationName, 4);
}
@Override
@SuppressWarnings({ "unchecked" })
public String serialize(String jsonInput) throws JsonProcessingException {
// Parse the input JSON string into a Map using Jackson
Map<String, Object> inputMap = objectMapper.readValue(jsonInput, Map.class);
// Format the body and indentation
String body = formatBody(inputMap, indentSize, indentSize);
String indentation = indent(indentSize);
return String.format("mutation {n%s%s(n%sn%s)n}", indentation, mutationName, body, indentation);
}
private static String formatBody(Map<String, Object> map, int indentSize, int currentIndent) {
return map.entrySet().stream()
.map(entry -> String.format(
"%s%s: %s",
indent(currentIndent + indentSize),
entry.getKey(),
formatValue(entry.getValue(), indentSize, currentIndent + indentSize)))
.collect(Collectors.joining("n"));
}
private static String formatValue(Object value, int indentSize, int currentIndent) {
if (value instanceof String) {
return """ + value + """;
} else if (value instanceof Number || value instanceof Boolean) {
return value.toString();
} else if (value instanceof Map) {
return String.format(
"{n%sn%s}",
formatBody((Map<String, Object>) value, indentSize, currentIndent),
indent(currentIndent));
} else {
throw new IllegalArgumentException("Unsupported value type: " + value.getClass());
}
}
private static String indent(int level) {
return " ".repeat(level);
}
}
</code>
<code>package org.example.graphql; import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class GraphQLMutationSerializer implements GraphQLSerializer { private final ObjectMapper objectMapper = new ObjectMapper(); private final String mutationName; private final int indentSize; public GraphQLMutationSerializer(String mutationName, int indentSize) { this.mutationName = mutationName; this.indentSize = indentSize; } public GraphQLMutationSerializer(String mutationName) { this(mutationName, 4); } @Override @SuppressWarnings({ "unchecked" }) public String serialize(String jsonInput) throws JsonProcessingException { // Parse the input JSON string into a Map using Jackson Map<String, Object> inputMap = objectMapper.readValue(jsonInput, Map.class); // Format the body and indentation String body = formatBody(inputMap, indentSize, indentSize); String indentation = indent(indentSize); return String.format("mutation {n%s%s(n%sn%s)n}", indentation, mutationName, body, indentation); } private static String formatBody(Map<String, Object> map, int indentSize, int currentIndent) { return map.entrySet().stream() .map(entry -> String.format( "%s%s: %s", indent(currentIndent + indentSize), entry.getKey(), formatValue(entry.getValue(), indentSize, currentIndent + indentSize))) .collect(Collectors.joining("n")); } private static String formatValue(Object value, int indentSize, int currentIndent) { if (value instanceof String) { return """ + value + """; } else if (value instanceof Number || value instanceof Boolean) { return value.toString(); } else if (value instanceof Map) { return String.format( "{n%sn%s}", formatBody((Map<String, Object>) value, indentSize, currentIndent), indent(currentIndent)); } else { throw new IllegalArgumentException("Unsupported value type: " + value.getClass()); } } private static String indent(int level) { return " ".repeat(level); } } </code>
package org.example.graphql;

import java.util.Map;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class GraphQLMutationSerializer implements GraphQLSerializer {
    private final ObjectMapper objectMapper = new ObjectMapper();

    private final String mutationName;
    private final int indentSize;

    public GraphQLMutationSerializer(String mutationName, int indentSize) {
        this.mutationName = mutationName;
        this.indentSize = indentSize;
    }

    public GraphQLMutationSerializer(String mutationName) {
        this(mutationName, 4);
    }

    @Override
    @SuppressWarnings({ "unchecked" })
    public String serialize(String jsonInput) throws JsonProcessingException {
        // Parse the input JSON string into a Map using Jackson
        Map<String, Object> inputMap = objectMapper.readValue(jsonInput, Map.class);

        // Format the body and indentation
        String body = formatBody(inputMap, indentSize, indentSize);
        String indentation = indent(indentSize);

        return String.format("mutation {n%s%s(n%sn%s)n}", indentation, mutationName, body, indentation);
    }

    private static String formatBody(Map<String, Object> map, int indentSize, int currentIndent) {
        return map.entrySet().stream()
                .map(entry -> String.format(
                        "%s%s: %s",
                        indent(currentIndent + indentSize),
                        entry.getKey(),
                        formatValue(entry.getValue(), indentSize, currentIndent + indentSize)))
                .collect(Collectors.joining("n"));
    }

    private static String formatValue(Object value, int indentSize, int currentIndent) {
        if (value instanceof String) {
            return """ + value + """;
        } else if (value instanceof Number || value instanceof Boolean) {
            return value.toString();
        } else if (value instanceof Map) {
            return String.format(
                    "{n%sn%s}",
                    formatBody((Map<String, Object>) value, indentSize, currentIndent),
                    indent(currentIndent));
        } else {
            throw new IllegalArgumentException("Unsupported value type: " + value.getClass());
        }
    }

    private static String indent(int level) {
        return " ".repeat(level);
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật