org.kohsuke.github 中是否有内置机制将 GHRepository 对象序列化为 JSON?

Is there a built in mechanism within org.kohsuke.github to serialize GHRepository objects to JSON?

我正在使用 org.kohsuke.github 中的 Java Github API 来检索 GHRepository 对象。我想将该对象序列化为 JSON。在 org.kohsuke.github 客户端中是否提供了执行此操作的方法?可能使用 Jackson?

目前,在使用 jackson 时,我必须创建自定义 pojo 以避免 Jackson 遇到空映射键和值。我怀疑这个 github 库已经有执行此操作的代码,因为我可以看到它在 GitHub.java 中序列化为 JSON,但我没有看到可以公开访问的利用它的方法。下面的代码遍历我所有组织中的所有回购以获得回购的 JSON 表示,然后将其存储在数据库中。

// Iterate over all orgs that I can see on enterprise
github.listOrganizations().withPageSize(100).forEach( org -> {

    // Get all the repositories in an org
    Map<String, GHRepository> ghRepositoryMap = org.getRepositories();

    // Iterate over each repo object and serialize
    for (Map.Entry<String, GHRepository> entry :ghRepositoryMap.entrySet()  ) {

        // Serialize to JSON
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //Handles null fields ok
        String jsonStr = objectMapper.writeValueAsString(entry.getValue()); // <-- this fails due to null key

    }
}

最后一行结果为:

com.fasterxml.jackson.databind.JsonMappingException: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) (through reference chain: org.kohsuke.github.GHRepository["responseHeaderFields"]->java.util.Collections$UnmodifiableMap["null"])

根据检查,我认为这不是唯一的 null 键。我可能可以通过添加 mixin 来处理它们来自定义它,但我正在 org.kohsuke.github 库中寻找一种内置方式,这使得这更容易,因为它似乎能够在内部执行此操作。

您应该实施并注册 NullKeySerializer。请参阅以下示例:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        Map<String, List<String>> map = new HashMap<>();
        map.put(null, Arrays.asList("A", "B", "C"));
        map.put("regular-key", Arrays.asList("X", "Y"));

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer());

        System.out.println(mapper.writeValueAsString(map));
    }
}

class NullKeySerializer extends JsonSerializer<Object> {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeFieldName("null");
    }
}

以上代码打印:

{
  "null" : [ "A", "B", "C" ],
  "regular-key" : [ "X", "Y" ]
}

此外,您不应为每个条目创建 ObjectMapper 实例。您可以创建一次并用于所有元素。