【问题标题】:JSON with pretty print打印漂亮的 JSON
【发布时间】:2014-05-19 21:16:12
【问题描述】:

我在 java 中创建了一个 JSONObject,并尝试使用 gson 的漂亮打印功能使该对象在网站上更具可读性,但它一直显示为;

{"Back Door":"Unlocked","Window 2":"Unlocked","Window 3":"Unlocked","Window 1":"Unlocked","Front Door":"Unlocked","System":"Disarmed","Lights":"On"}

这是我目前使用 gson-2.2.4-javadoc.jar、gson.2.2.4-sources.jar 和 gson.2.2.4 jar 文件得到的代码;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Get("json")
public String handleGet() {
    try {
        JSONObject system = new JSONObject();

        system.put("System", "Disarmed");
        system.put("Front Door", "Unlocked");
        system.put("Back Door", "Unlocked");
        system.put("Window 1", "Unlocked");
        system.put("Window 2", "Unlocked");
        system.put("Window 3", "Unlocked");
        system.put("Lights", "On");

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println( gson.toJson(system) );

        JsonRepresentation jsonRep = new JsonRepresentation(system);

        return jsonRep.getText();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}

编辑

像这样编辑代码后;

Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println( gson.toJson(system) );

//JsonRepresentation jsonRep = new JsonRepresentation(system);

String pretty = gson.toJson(system);
return pretty;

//return jsonRep.getText();

} catch (JSONException e) {
e.printStackTrace();
//} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}

现在它显示为;

{
  "map": {
    "Back Door": "Unlocked",
    "Window 2": "Unlocked",
    "Window 3": "Unlocked",
    "Window 1": "Unlocked",
    "Front Door": "Unlocked",
    "System": "Disarmed",
    "Lights": "On"
  }
}

有什么办法可以把'map'改成'system'?

【问题讨论】:

    标签: java json pretty-print


    【解决方案1】:

    只返回漂亮打印的 Gson 输出

    String pretty = gson.toJson(system);
    return pretty;
    

    有什么价值

    {
      "Lights": "On",
      "Front Door": "Unlocked",
      "Window 3": "Unlocked",
      "Window 2": "Unlocked",
      "System": "Disarmed",
      "Back Door": "Unlocked",
      "Window 1": "Unlocked"
    }
    

    【讨论】:

    • 谢谢它的工作!但它显示为; {“地图”:{“后门”:“解锁”,“窗口 2”:“解锁”,“窗口 3”:“解锁”,“窗口 1”:“解锁”,“前门”:“解锁” , "System": "Disarmed", "Lights": "On" } } 我可以把'map'改成别的吗?像“系统”。
    • @user3506728 你能在你的问题中添加一个编辑来显示你做了什么吗?
    • @user3506728 这就是JSONObject 中的地图的命名方式。如果你不能在那里改变它,那么就没有办法在 JSON 中改变它。否则,您会使用 GSON 中断反序列化。
    • @user3506728 抱歉,我使用了错误的JSONObject 类。如果您已经在使用 Gson,不妨创建一个 POJO 并将其序列化。
    猜你喜欢
    • 2021-01-31
    • 2014-05-12
    • 2017-11-03
    • 2011-05-05
    • 2017-05-01
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多