如何在 Spring 控制器 Json 响应中连字符复合属性名称 Katharsis.io

How to hyphen compound attribute names in a Spring Controllers Json response with Katharsis.io

Json:API要求建议使用连字符连接复合属性名称(如名字)

...
{
"type": "people",
"id": "9",
"attributes": {
  "first-name": "Foo",
  "last-name": "Bar",
}
...

在 Java 中,带连字符的属性名称不是有效标识符。

我正在使用 Katharsis 2.0.1 在 spring-boot 1.3.0 中构建一个基于 JSON:API 的服务后端。我的 calling/consuming 前端应用程序是使用 Ember 2.0 和 ember-data.

构建的

不幸的是,Katharsis 似乎没有将 Java 中的复合属性名称转换为 Json 中的带连字符的属性名称。

这是 Katharsis 为资源生成的结果 GET /api/customers

{
 "data": [
   {
     "type": "customers",
     "id": "1",
     "attributes": {
       "cpn": "-1234567",
       "firstName": "John",
  },
  ...

但应该是"first-name":"John"

我是否遗漏了某些配置或如何告诉 Katharsis 使用连字符属性?

谢谢!

JSON:API 不要求多词属性使用连字符;他们只是 recommends

在我看来,由于您所描述的原因,该建议是愚蠢的。它只会使互操作性变得更加困难。所以我的建议是忽略建议并坚持使用驼峰式属性。同样,没有任何事情是被禁止的。

一些(愚蠢的)工具可能会假定您的 API 遵循破折号的建议。但是,如果一个工具假设了这一点,并且没有给你一种方法来覆盖这个假设,那么它就是该工具中的一个错误,你将通过向工具的作者展示他们需要支持所有有效的工具来帮助社区JSON:API 用法,而不仅仅是遵循建议的用法。

P.S。虽然以上只是我的 opinion/advice,但我是 JSON:API 的编辑之一,所以这是一个有见地的意见,我提到的事实(例如关于 dasherizing 只是一个建议)是正确的。

按照@Ethans 的建议,我坚持使用 Katharsis.io 中的驼峰式属性,并让 Ember 覆盖属性名称。

在 Ember 中,JSONAPISerializer 支持所有情况,因为它提供了易于覆盖的挂钩。 keyForAttribute and keyForRelationship 的文档显示了如何自定义键的示例。

在我的例子中,我必须实现以下序列化程序 class:

// app/application/serializer.js or app/serializers/application.js 

import Ember from 'ember';
import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
 keyForAttribute: function(attr, method) {
  return Ember.String.camelize(attr);
},

 keyForRelationship: function(key, relationship, method) {
  return Ember.String.camelize(key);
 }
});

在最新版本中添加了对来自 jackson 的 PropertyNamingStrategy 的支持,因此连字符名称可用。