JSON有漂亮的印刷品

时间:2014-04-07 14:41:41

标签: java json pretty-print

我在java中创建了一个JSONObject,并且正在尝试使用gson中的漂亮的print函数来使对象在网站上更具可读性,但它仍然显示为;

{"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"
  }
}

有没有办法改变地图'到'系统'?

1 个答案:

答案 0 :(得分:2)

只需返回漂亮的印刷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"
}