Java GSON简单写Json To string

时间:2013-12-03 23:10:56

标签: java gson

我正在寻找如何使用GSON制作SIMPLE JSON字符串。所有示例都需要将输出写入文件,我只想将其放入字符串中。

我想创建一个像这样的JSON字符串:

{"status":"success","error":"FULL ERROR"}

1 个答案:

答案 0 :(得分:3)

我看不出是什么问题

public static void main(String[] args) throws Exception {
    CustomBean customBean = new CustomBean();
    customBean.error = "FULL ERROR";
    customBean.status = "success";
    Gson gson = new Gson();
    System.out.println(gson.toJson(customBean));
}

public static class CustomBean {
    private String status;
    private String error;
}

打印

{"status":"success","error":"FULL ERROR"}

我认为你应该通过Gson javadoc.

如果您不想要新课程,可以

JsonObject object = new JsonObject();
object.addProperty("status", "success");
object.addProperty("error", "FULL ERROR");
System.out.println(object);

也打印

{"status":"success","error":"FULL ERROR"}