gpt4 book ai didi

java - JSON 与 pretty-print

转载 作者:行者123 更新时间:2023-12-02 05:57:53 25 4
gpt4 key购买 nike

我用java制作了一个JSONObject,并尝试使用gson的 pretty-print 功能来使该对象在网站上更具可读性,但它一直显示为;

{"后门":"已解锁","窗口 2":"已解锁","窗口 3":"已解锁","窗口 1":"已解锁","前门":"已解锁","系统":"撤防","灯":"开"}

这是我迄今为止使用 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 ”更改为“系统”吗?

最佳答案

只需返回打印精美的 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"
}

关于java - JSON 与 pretty-print ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22915640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com