簡體   English   中英

將簡單 json 字符串中所有項目的鍵和值打印到控制台

[英]Print key and value of all items in simple json string to console

我有以下內容,我可以打印出每個屬性。 很簡單,但是有沒有一種簡單的方法可以打印 JSON 字符串中每個項目的鍵和值? 只需在控制台中打印鍵和值。

private static void deserializeUserSimple() {
    String userJson = "{\"name\":\"smithy\",\"email\":\"blah@gmail.com\",\"age\":21,\"isDeveloper\":true}";

    Gson gson = new Gson();
    UserSimple userSimple = gson.fromJson(userJson, UserSimple.class);

     // this prints but looking for easy way to print all key and values
    System.out.println(userSimple.name);
}
String userJson = "{\"name\":\"smithy\",\"email\":\"blah@gmail.com\",\"age\":21,\"isDeveloper\":true}";
JsonObject convertedObject = new Gson().fromJson(userJson, JsonObject.class);
for(String key:convertedObject.keySet()){
            System.out.println("Key - " + key);
            System.out.println("Value - " + convertedObject.get(key));
}

Output:

Key - name
Value - "smithy"
Key - email
Value - "blah@gmail.com"
Key - age
Value - 21
Key - isDeveloper
Value - true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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