简体   繁体   English

JSON有漂亮的印刷品

[英]JSON with pretty print

I made a JSONObject in java and are trying to use the pretty print function from gson to made the object more readable on the website, but it keeps showing as; 我在java中创建了一个JSONObject,并尝试使用gson中的漂亮的print函数使对象在网站上更具可读性,但它仍然显示为;

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

This is the code I've got so far using gson-2.2.4-javadoc.jar, gson.2.2.4-sources.jar and gson.2.2.4 jar files; 这是我到目前为止使用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;
}

EDIT 编辑

after editing the code like this; 编辑完这样的代码之后;

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

and now it shows as; 现在它显示为;

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

Is there any way to change 'map' to 'system'? 有没有办法将'map'改为'system'?

Just return the pretty printed Gson output 只需返回漂亮的印刷Gson输出

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

which has the value 哪个有价值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM