JsonObject JsonArray:获取值并生成json

时间:2015-05-26 09:57:19

标签: java json

这种格式是我想要的:

{"data": [{"name": "Sky","account": "k@gmail.com","edit": "1","delete": "1"}]}

现在我的jsonArray是:

 {"name":"Sky","delete":1,"edit":1,"account":"k@gmail.com"}

下一步是什么? 请帮助我或是否有更好的解决方案
请告诉我谢谢

public String getList() throws JSONException {

        User dataUser  =memberO.getMember(1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", dataUser.getUserName());
        jsonObject.put("account", dataUser.getAccount());
        jsonObject.put("edit", dataUser.getUserId());
        jsonObject.put("delete", dataUser.getUserId());

        JSONArray jsonArray = new JSONArray();

        System.out.println(jsonArray);

        String str = "{\"data\": [{\"name\": \""+dataUser.getUserName()+"\",\"account\": \""+dataUser.getAccount()+"\",\"edit\": \""+dataUser.getUserId()+"\",\"delete\": \""+dataUser.getUserId()+"\"}]}";

        return str;


    }

3 个答案:

答案 0 :(得分:0)

您可以直接将JSONObject转换为String

    JSONObject jObject = new JSONObject();
    jObject.put("data", jsonArray);

    String jsonText = jObject.toJSONString();
    System.out.println(jsonText); 

答案 1 :(得分:0)

试试这个......这会对你有帮助

public String getList() throws JSONException {

    User dataUser  =memberO.getMember(1);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", dataUser.getUserName());
    jsonObject.put("account", dataUser.getAccount());
    jsonObject.put("edit", dataUser.getUserId());
    jsonObject.put("delete", dataUser.getUserId());

    JSONArray jsonArray = new JSONArray();
    jsonArray.add(jsonObject);


    JSONObject responseJson = new JSONObject();
    responseJson.put("data", jsonArray);//Here you can see the data in json format

    return responseJson.toString();


}

答案 2 :(得分:0)

public String getList() throws JSONException {

    User dataUser  =memberO.getMember(1);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", dataUser.getUserName());
    jsonObject.put("account", dataUser.getAccount());
    jsonObject.put("edit", dataUser.getUserId());
    jsonObject.put("delete", dataUser.getUserId());

    JSONArray jsonArray = new JSONArray();

    jsonArray.put(0, jsonObject);
    JSONObject topObject = new JSONObject();
    topObject.put("data", jsonArray);
    System.out.println(topObject.toJSONString);
    System.out.println(jsonArray);

    String str = "{\"data\": [{\"name\": \""+dataUser.getUserName()+"\",\"account\": \""+dataUser.getAccount()+"\",\"edit\": \""+dataUser.getUserId()+"\",\"delete\": \""+dataUser.getUserId()+"\"}]}";

    return str;


}