Jackson: Serializing/Deserializing String to Array with single entry

大憨熊 提交于 2019-12-11 05:39:46

问题


I am currently writing a Java client that consumes a RESTful service, using the Restlet package and its Jackson extension. I want to query the service for a user and deserialize the response to a User POJO that looks as follows:

@JsonIgnoreProperties(ignoreUnknown=true)
public class User {

    private Integer uid;    
    private String name;
    private String mail;
    private String field_nickname;

    // omitted for brevity: getters/setters, toString
}

A sample response from the service looks as follows:

{
    "uid": "5",
    "name": "John Doe",
    "mail": "john@example.com",
    "field_nickname": {
        "und": [{
            "value": "jdoe",
            "format": null,
            "safe_value": "jdoe"
        }]
    }
}

Here is the Java client code:

import org.restlet.resource.ClientResource;
public class TestClient {

    public static void main(String[] args) throws Exception {
        // Getting a User
        ClientResource cr = new ClientResource("http://localhost/rest/user/7.json")
        User user = cr.get(User.class);
        System.out.println(user);

        // Creating a User
        cr = new ClientResource("http://localhost/rest/user.json");
        User user = new User();
        user.setName("Jane Doe");
        user.setFieldNick("jdoe2");
        user.setMail("jdoe2@example.com");
        cr.post(user);
    }

The serialization/deserialization of the uid, name and mail fields is very straightforward and poses no problems. My problem is with field_nickname: The field always contains the array und with a single entry that always looks the same.

How can I tell Jackson to deserialize this field to a String that holds the value of field_nickname[und][0][value] and serialize the attribute into such an array?


回答1:


This is kind of one-off structural transformation that you will need to write your own handler. The easiest way is probably just to implement something like:

@JsonProperty("field_nickname")
public void setNickname(NicknameWrapper[] wrapper) {
   field_nickname = wrapper[0].value;
}

@JsonIgnoreProperties(ignoreUnknown=true)
static class NicknameWrapper {
   public String value;
}

and perhaps reverse (getNickname()) as well.



来源:https://stackoverflow.com/questions/12892306/jackson-serializing-deserializing-string-to-array-with-single-entry

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