【发布时间】: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