簡體   English   中英

JSON有漂亮的印刷品

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM