[英]JSON with 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"
}
}
有没有办法将'map'改为'system'?
只需返回漂亮的印刷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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.