Jackson:使用单个条目序列化/反序列化字符串到数组 [英] Jackson: Serializing/Deserializing String to Array with single entry

查看:111
本文介绍了Jackson:使用单个条目序列化/反序列化字符串到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个使用Restlet软件包及其Jackson扩展程序来使用RESTful服务的Java客户端。
我想查询用户的服务,并将响应反序列化为用户 POJO,如下所示:

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"
        }]
    }
}

以下是Java客户端代码:

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

uid的序列化/反序列化 name mail 字段非常简单,没有任何问题。
我的问题是 field_nickname :该字段始终包含数组 und ,其中包含一个始终显示的条目同样。

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.

如何告诉Jackson将此字段反序列化为 String ,其值为 field_nickname [und] [0] [value] 并将属性序列化为这样的数组?

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?

推荐答案

这是一种一次性的结构转换,你需要编写自己的处理程序。最简单的方法可能只是实现类似的东西:

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

也可能反转(getNickname())。

and perhaps reverse (getNickname()) as well.

这篇关于Jackson:使用单个条目序列化/反序列化字符串到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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