0

我有一个有点奇怪的问题。我有一个庞大的数据对象系统,具有多种属性。它们正在使用 JSON 进行序列化和反序列化,并且在许多情况下,字段名称已被注释更改。我有一些用户与该 JSON 进行交互,他们并不关心底层代码的作用,只要他们知道在 JSON 中放置什么以使其正常工作。我想为他们提供一个他们可以访问的端点,在那里他们可以识别一个类,并让它返回字段名称(就像它出现在序列化的 JSON 中一样)。我有类对象并且有一些使用反射的能力。

我考虑了几个选项。我最初的计划是我将通过反思来处理所有事情,但我意识到这将需要我自己去寻找所有影响杰克逊的注释,以试图让逻辑正确。这听起来像是大量不必要的努力,几乎肯定会产生一些丑陋且隐藏得很好的错误,因为我最终得到的逻辑不太正确。毕竟杰克逊已经有了这个逻辑。看来我应该能够以某种方式利用它。

我考虑过制作该类的虚拟版本,对其进行序列化,然后从生成的 JSON 中读取字段名称,但是这里有大量的类,其中许多很复杂,其中许多具有指向的属性在彼此。在这种情况下,使那种字段自动填充可以使其正常工作......好吧,这听起来也像是大量的希望不必要的、产生错误的工作。

杰克逊某处的逻辑知道如何识别这些字段名称(特别是实际正在序列化的字段的序列化字段名称)。似乎应该可以仅使用 ObjectMapper 和我想要信息的类来确定。可能吗?我该怎么做?我一直无法在网上找到说明(所有关于如何更改名称的文章都被弄糊涂了),仅仅阅读杰克逊的类文件也没有奏效。(评论相对简洁,我要找的东西非常具体。即使我找到了,我也不知道如何确保它实际上给了我我需要的东西,而不是其他东西,非常相似的东西。)

作为奖励,如果有某种方法可以知道该字段具有哪个 java 类作为其值,那就更好了,但我至少有一些解决方法,我认为我可能能够使其可行。获得精确的字段名称更为重要。

4

1 回答 1

0

好吧,我设法找到了答案。

// We're using the jacksObjectMapper to grab the serializer, so that
// we can get the list of logical properties from said serializer.
// The point of this process is that we want to give the user the
// data that corresponds with what said user is looking at.  That
// means we specifically want the fields that jackson will serialize
// and deserialize, with the names that jackson will use.  This is
// the way to get that.  It was not as easy to find as you might think.

SerializerProvider serProv = jacksonObjectMapper.getSerializerProviderInstance();
JsonSerializer serializer = serProv.findValueSerializer(inputClass);

Iterator<PropertyWriter> logicalProperties = serializer.properties();

// Once we have the logical properties, we grab the field names and 
// value classes from that, and use that to populate everything else.
while (logicalProperties.hasNext()) {

    PropertyWriter propw = logicalProperties.next();
    String jsonFieldName = propw.getName();
    ...
}

现在过了这一点,将它与生成属性的 java 反射字段对齐仍然有点有趣,这样我就可以真正获得这些值类,但这是一个不同的问题,并且有更多的解决方案取决于个人代码库。

于 2020-10-08T20:09:23.907 回答