How to work with readonly props in REST API?

蹲街弑〆低调 提交于 2019-12-11 19:23:23

问题


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;
}

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');
        });
    }
}

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

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

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)?


回答1:


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.



来源:https://stackoverflow.com/questions/17407823/how-to-work-with-readonly-props-in-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!