Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

java - JAX-RS, Map<String,String> to JSON without the overhead?

I'm using JAX-RS to create restful webservices in Java. I am getting to much overhead in the produced JSON.

Data class:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Test {

    private Map<String,String> data;

    Test() {}

    public Test(Map<String,String> data) {
        this.data = data;
    }

    public Map<String, String> getData() {
        return data;
    }
}

Service:

@GET
@Path("/test")
@Produces("application/json; charset=UTF-8;")
public Test test() {
   Map<String,String> map = new HashMap<String,String>();
   map.put("foo", "bar");
   map.put("bingo", "bongo");
   return new Test(map);
}

Produces:

{"data":{"entry":[{"key":"foo","value":"bar"},{"key":"bingo","value":"bongo"}]}}

I would like it to produce:

{"data":{"foo":"bar","bingo":"bongo"}}

What is the simplest way to achive this? I am free to redifine my data class but I can't know in advance the keys or size of the map.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simplest way would be using List<Pair> instead where Pair is just a Javabean with two properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...