在java中构建Json字符串?

时间:2017-09-04 09:41:37

标签: java json string

我正在尝试在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"
 }
}

我应该怎么做?

2 个答案:

答案 0 :(得分:2)

您需要使用JSONArrayJsonArrayBuilder来映射这些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();

答案 1 :(得分:0)

您可以使用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;
    }
}

}

和下一个complite数据并生成json:

    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));