Marshal a java.util.Map

时间:2021-12-07 00:50:32

The next question for my restful JSON Service.

我的宁静JSON服务的下一个问题。

import java.util.Map;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Martin Burchard
 * 
 */
@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
    private String id;
    private String nickname;
    private String email;
    private String password;
    private Map<String, String> user_attributes;

}

Currently the service delivers the following JSON (indented for better reading):

目前,该服务提供以下JSON(缩进以便更好地阅读):

{
    "user" : {
        "id" : "9bdf40ea-6d25-4bc3-94ad-4a3d38d2c3ca",
        "email" : "test.user@test.de",
        "password" : "xXpd9Pl-1pFBFuX9E0hAYGSDTyJQPYkOtXGvRCrEtMM",
        "user_attributes" : {
            "entry" : [{
                    "key" : "num",
                    "value" : 123
                }, {
                    "key" : "type",
                    "value" : "nix"
                }
            ]
        }
    }
}

The funny think is, internally the num 123 is a java.lang.String...

有趣的是,内部数字123是java.lang.String ...

I don't understand what is explained here http://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-DealingwithJSONarrayserializationissues

我不明白这里解释了什么http://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-DealingwithJSONarrayserializationissues

I like to have this JSON:

我喜欢这个JSON:

{
    "user" : {
        "id" : "9bdf40ea-6d25-4bc3-94ad-4a3d38d2c3ca",
        "email" : "test.user@test.de",
        "password" : "xXpd9Pl-1pFBFuX9E0hAYGSDTyJQPYkOtXGvRCrEtMM",
        "user_attributes" : {
            "num" : "123",
            "type" : "nix"
        }
    }
}

I changed the JSON provider to Jackson. Now my JSON looks like I like it...

我将JSON提供程序更改为Jackson。现在我的JSON看起来像我喜欢它...

2 个解决方案

#1


1  

The only thing that comes to my mind is to use JAXB XmlAdapter. You can define how a given object (in your case Map) would be mapped to JSON string.

我唯一想到的就是使用JAXB XmlAdapter。您可以定义给定对象(在您的情况下为Map)如何映射到JSON字符串。

#2


0  

Use a proper JSON library like Jackson

使用像杰克逊这样的JSON库

#1


1  

The only thing that comes to my mind is to use JAXB XmlAdapter. You can define how a given object (in your case Map) would be mapped to JSON string.

我唯一想到的就是使用JAXB XmlAdapter。您可以定义给定对象(在您的情况下为Map)如何映射到JSON字符串。

#2


0  

Use a proper JSON library like Jackson

使用像杰克逊这样的JSON库