我在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"
}
}
有什么办法可以将“地图”更改为“系统”?
最佳答案
只需返回漂亮的打印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"
}