在java中构建Json字符串?

在java中构建Json字符串?,java,json,string,Java,Json,String,我试图用java构建一个json字符串,但我有点困惑,不知该怎么做。这就是我到目前为止所尝试的 String jsonString = new JSONObject() .put("JSON1", "Hello World!") .put("JSON2", "Hello my World!") .put("JSON3", new JSONObject()

我试图用java构建一个json字符串,但我有点困惑,不知该怎么做。这就是我到目前为止所尝试的

String jsonString = new JSONObject()
                  .put("JSON1", "Hello World!")
                  .put("JSON2", "Hello my World!")
                  .put("JSON3", new JSONObject()
                       .put("key1", "value1")).toString();

System.out.println(jsonString);
输出为:

{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}
我想要的Json如下:-

{
 "data":{
    "nightclub":["abcbc","ahdjdjd","djjdjdd"],
    "restaurants":["fjjfjf","kfkfkfk","fjfjjfjf"],


    "response":"sucess"
 }
}
我应该怎么做呢?

您需要使用和映射这些json数组

这是您需要使用的代码:

    String jsonString = new JSONObject()
        .put("data", new JSONObject()
            .put("nightclub", Json.createArrayBuilder()
                    .add("abcbc")
                    .add("ahdjdjdj")
                    .add("djdjdj").build())
            .put("restaurants", Json.createArrayBuilder()
                    .add("abcbc")
                    .add("ahdjdjdj")
                    .add("djdjdj").build())
            .put("response", "success"))
                    .toString();
您可以使用gson-lib

首先创建pojo对象:

public class JsonReponse {

private Data data;

public Data getData() {
    return data;
}

public void setData(Data data) {
    this.data = data;
}

public class Data {

    private String reponse;
    private List<String> nightclub;
    private List<String> restaurants;

    public String getReponse() {
        return reponse;
    }

    public void setReponse(String reponse) {
        this.reponse = reponse;
    }

    public List<String> getNightclub() {
        return nightclub;
    }

    public void setNightclub(List<String> nightclub) {
        this.nightclub = nightclub;
    }

    public List<String> getRestaurants() {
        return restaurants;
    }

    public void setRestaurants(List<String> restaurants) {
        this.restaurants = restaurants;
    }
}

对于列表,您可以使用JSONArray而不是JSONObject。您至少应该做一点努力来生成与您需要的类似的JSON输出。现在看来,“这就是我迄今为止所尝试的”是一个复制粘贴的Hello World示例,而您自己还没有尝试过任何东西。此外,还不清楚您是在问如何获得良好的格式,还是在问如何将嵌套对象和数组放入“JSONObject”中。请澄清。
    JsonReponse jsonReponse = new JsonReponse();
    JsonReponse.Data data = jsonReponse.new Data();
    data.setReponse("sucess");
    data.setNightclub(Arrays.asList("abcbc","ahdjdjd","djjdjdd"));
    data.setRestaurants(Arrays.asList("fjjfjf","kfkfkfk","fjfjjfjf"));
    jsonReponse.setData(data);

    Gson gson = new Gson();
    System.out.println(gson.toJson(jsonReponse));