[英]How do I convert a JsonArray of JsonString to a List of String
這個問題的范圍是 The Java API for JSON Processing (JSR 353)。
給定元素為 JsonString 的 JsonArray,如何輕松將其轉換為List<String>
或a Set<String>
? 對於Set<String>
,我們假設 JsonArray 包含一個唯一的字符串值集合。
假設我有一個這樣的 JSON 對象:
{
"name" : "James Johns",
"street" : "22 Nancy St.",
"emails" : [
"james@a.com",
"james@b.net",
null,
""
]
}
我希望我的結果集合忽略電子郵件數組中的任何空或空字符串條目。
假設我的 JsonObject 實例已經創建。
JsonObject person = <parse the JSON input>;
JsonArray emails = person.get("emails");
我一直對 JsonValue 和 JsonString 感到困惑,並試圖獲取實際的 String 值。 如果我使用JsonValue.toString()
和JsonString.toString()
方法,我會得到包含雙引號的字符串值,就好像原始 JSON 是"\\"james@a.com\\""
。 我需要字符串值是等效的 JSON 值"james@a.com"
。
使用 Java 8,可以輕松地將 JsonString 的 JsonArray 轉換為如下所示的列表:
JsonObject person = <parse the JSON input>;
List<String> emailList =
Optional.ofNullable(person.getJsonArray("emails"))
.orElse(JsonValue.EMPTY_JSON_ARRAY) // Use an empty list if the property's value was null
.getValuesAs(JsonString::getString) // Get each JsonString entry as String
.stream() // Turn the collection into a stream for filter/collect
.filter(email -> email!=null && !email.isEmpty()) // Exclude any null/empty entries
.collect(Collectors.toList()); // Create the List
ofNullable/orElse
組合保證我得到一個 JsonArray,即使該數組為空,從而避免任何空指針異常的考慮。getValuesAs(JsonString::getString)
是一個 JsonArray 方法,它通過將JsonString.getString()
方法應用於每個返回的 JsonString 來返回一個列表。 所述JsonString.getString()
方法返回字符串值“james@a.com”,而不是“\\” james@a.com \\“”值,該值的JsonString.toString()
方法返回。stream()
方法將集合轉換為一個順序流,我們可以使用它來過濾和收集原始集合的成員。filter()
方法將 Predicate email -> email!=null && !email.isEmpty()
應用於流中的每個條目,丟棄任何空條目或空字符串條目。collect()
方法將過濾后的條目收集到指定的集合類型中。 要獲取Set<String>
,請更改.collect()
以使用:
.collect(Collectors.toSet())
一旦您習慣了 Java 8 機制,這種方法就提供了一種簡潔、易於閱讀和理解的技術來操作集合,而無需更復雜的空/空檢查和使用 for 循環方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.