Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal a java.util.Map<String,String>

The next question for my restful JSON Service.

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

{
    "user" : {
        "id" : "9bdf40ea-6d25-4bc3-94ad-4a3d38d2c3ca",
        "email" : "[email protected]",
        "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...

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

I like to have this JSON:

{
    "user" : {
        "id" : "9bdf40ea-6d25-4bc3-94ad-4a3d38d2c3ca",
        "email" : "[email protected]",
        "password" : "xXpd9Pl-1pFBFuX9E0hAYGSDTyJQPYkOtXGvRCrEtMM",
        "user_attributes" : {
            "num" : "123",
            "type" : "nix"
        }
    }
}

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

like image 607
Nabor Avatar asked Nov 13 '22 06:11

Nabor


1 Answers

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.

like image 171
Piotr Kochański Avatar answered Nov 16 '22 04:11

Piotr Kochański