如何在REST API只读道具工作? [英] How to work with readonly props in REST API?

查看:133
本文介绍了如何在REST API只读道具工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的REST API,揭露做了一些只读域的资源。这些字段由系统自动计算,并在JSON重新presentation暴露出来,他们是一个域实体的一部分。结果
我已经使用这个框架在这赢得成功(的 JacksonMapper 的),在该计算结果,如该方法的注释:

I have my REST API that expose a resource made of some readonly fields. These fields are calculated automatically from the system and exposed in the JSON representation, and they are part of a domain entity.
I've succed in this using the framework (JacksonMapper) annotation on the method that calculate the result, like:

@JsonProperty
public boolean isAnonymous(){
    //some logic
    return result;
}

,直到这些资源用于读的目的,一切它的确定,当我有写操作时,更新例如,对于工作问题上升。结果
问题是,该框架我使用的客户(的 angularjs 的),发送也这些字段来更新API时我搜索资源修改和更新,例如:

Untill these resource are used for read purpose, everything it's ok, the problems rise when I have to work with write operations, the update for example.
The problem is that the framework I use for the client (angularjs), send also these fields to the update API when I search for a resource modify, and update it, ex:

function test(MyResource){
    MyResource.get({id: 0}, function(myResource){
        myResource.writeableProperty = 'modified';
        myResource.$update(function(res){
             console.log('everything went ok');
        });
    }
}

在此情况下,问题是通过JSON发送的的用于更新:

In this case the problem is the JSON sent by angular for the update:

{
    "id": 0,
    "writeableProperty": "modified"
    "anonymous": true
}

在这种情况下,JSON的反序列化失败,因为与匿名属性的问题,这并不在我的域实体存在。结果
所以,我该怎么管理这些只读属性,是不是有这种不同于你从服务器已经和您什么都发送到服务器的JSON的RA presentation?结果
或者,也许这是更好地使用不同的资源,使得有可能派出也是财产,在我的应用程序中创建一个相关的DTO,而忽略它的财产(或发送一个错误,如果有人试图改变它)?

In this case the deserialization of the JSON fail, due a problem with that anonymous property that doesn't exist in my domain entity.
So, how can I manage these readonly property, is it right to have the rapresentation of the JSON that differs from what you have from the server and what you have to send to the server?
Or maybe it's better to use a different resource, make possible to sent also that property, creating a related DTO in my application, and ignore the property on it (or send an error if someone try to change it)?

推荐答案

如果你想忽略对服务器端的这个属性,你不能使用 JsonIgnoreProperties 注释。

If you want to ignore this property on the server-side, you cant use the JsonIgnoreProperties annotation.

@JsonIgnoreProperties(ignoreUnknown=true)
public class MyObject {
   ....
}

这将系列化只在你的类声明的属性。

This will serialize only attributes that was declared in your class.

这篇关于如何在REST API只读道具工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆