改变JSON格式

时间:2017-08-31 09:27:48

标签: java json spring web-services

使用spring我创建了一个这个webservice

@POST
    @Path("/get_user_info")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public List<GetUserInfoResponse> get_User_Info(GetUserInfoRequest request) throws Exception;

这会给我一个GetUserInfoResponse这样的列表

enter image description here

问题:是否有可能得到像这样的JSON? :

enter image description here

类:GetUserInfoResponse

package com.audaxis.compiere.ws.bean.response;

//Same imports

@XmlRootElement(name="infos")
@XmlType(propOrder={"key", "values"})
public class GetUserInfoResponse {

    private int key;
    private List<GetUserInfo> values;

   //Same Constructor
   //Same getters && setters
}

类:GetUserInfo

   package com.audaxis.compiere.ws.bean;
    //Same imports

    @XmlRootElement(name="values")
    @XmlType(propOrder={"columnName", "old_value", "new_value", "status", "motif"})
    public class GetUserInfo {

        private String columnName;
        private String old_value;
        private String new_value;
        private String status;
        private String motif;

//Same Constructor
//Same getters && setters

 }

这是我的计划:

methode(){
    List<GetUserInfoResponse> responses = new ArrayList<GetUserInfoResponse>();
    while(rs.next()){
    GetUserInfoResponse response = new GetUserInfoResponse();
      for (X_Z_WS_Column column : columns) {
        GetUserInfo info = new GetUserInfo();
        //setinfo
        infos.add(info);
    }
    response.setValues(infos);
    responses.add(response);
   }
   return responses
 }

1 个答案:

答案 0 :(得分:1)

这是制作json对象并填充它的基本java代码。

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class test {
    public static void main(String[] args) {

        JSONObject obj = new JSONObject();
        obj.put("key", "city");

        JSONArray list = new JSONArray();
        list.add("Delhi");
        list.add("Mumbai");
        list.add("Bangalore");
        obj.put("value", list);

        System.out.print(obj);

    }

}

如果您对格式有任何疑问,欢迎您提出。 输出是:

{&#34;值&#34;:[&#34;德里&#34;&#34;孟买&#34;&#34;班加罗尔&#34],&#34;键&#34; :&#34;城市&#34;}