简体   繁体   中英

REST - How to minify Json Response

I have a JAVA REST service that returns a list of objects. Each object contains name, description, code. I want to minify response json

{
    "objects": {
        "count": 10000,
        "list": [
            {
                "name": "1",
                "description": "foo",
                "code": "foo",
            },
            {
                "name": "2",
                "description": "bar",
                "code": "bar",
            },
            ...... (1.000 items)
        ]
    }
}

TO:

{
    "a": {
        "b": 1000,
        "c": "a:objects,b:count,c:mapping,d:list,e:name,f:description,g:code",
        "d": [
            {
                "e": "1",
                "f": "foo",
                "g": "foo",
            },
            {
                "e": "2",
                "f": "bar",
                "g": "bar",
            },
            ...... (1.000 items)
        ]
    }
}

how can i do it, thanks.

Even though we don't know what specific technologies you are using. I am going to make an assumption that you are using some sort of REST library like Spring or JaxRS and you are serializing POJOs into the JSON. I will also make the assumption that you have everything setup and working for that configuration and I will focus on the output specifically using that setup.

If you are using something like Jackson for your POJO, you can add the following Annotation to your class:

public class MyResponseObject {
    @JsonProperty("a")
    private MyObject objects;

    public MyObject getObjects() { return objects; }
    public void setObjects(MyObject object) { this.objects = object; }
}

public class MyObject {
    @JsonProperty("b")
    private long count;
    @JsonProperty("d")
    private List<Item> list;

    // getters/setters
}

public class Item {
    @JsonProperty("e")
    private Sting name;
    @JsonProperty("f")
    private String description;
    @JsonProperty("g")
    private String code;

    // getters/setters
}

In regards to the mapping of what each of those mean, you can hard/code that mapping, but I don't think there is an automatic way to do that. You can also include what that mapping is in the JavaDoc for your method. Another alternative is if this is an API that is public to other services, you can not only provide documentation, but also a packaged Jar with the POJOs that your API puts out. This way all they have to do is include your jar file as a dependency and include them in the mapped classes.

I hope this helps guide you in the right direction.

Also, if you don't use Jackson, but prefer JAXB use @XmlElement(name="a")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM