簡體   English   中英

對象的JSON數組到字符串列表

[英]JSON Array on Objects to List of String

我有以下JSON

[{
    "rowId": "03 EUR10580000"
}, {
    "rowId": "03 EUR10900001"
}, {
    "rowId": "03 EUR1053RUD*"
}, {
    "rowId": "033331"
}]

並且我想將其轉換為僅包含rowId值的字符串列表,因此在這種情況下

"03 EUR10580000"
"03 EUR10900001"
"03 EUR1053RUD*"
"033331"

我是用Gson fromJson做到的,但作為回報,我得到了LinkedTreeMap的列表,當我執行循環失敗時。 我想要一個簡單的字符串列表。

好吧,您的字符串不是“字符串列表”的json。 它包含對象列表。 因此,您可以做的是創建一個以rowID作為字符串屬性的類。

類數據

  • rowID(字符串類型)

然后你可以使用GSON解析此JSON字符串為List <數據>的使用這里

或者您必須手動准備一個新的json解析器。

如果只想使用Gson快速解析字符串,則可以簡單地創建構建器,並使用“默認” ListMap實例來表示Java中的JSON 如果要更安全地使用類型,或者要在“較大”的項目中使用已解析的實例,則建議按照其他答案中的說明創建一個POJO。

final GsonBuilder gsonBuilder = new GsonBuilder();

// you may want to configure the builder

final Gson gson = gsonBuilder.create();

/*
 * The following only works if you are sure that your JSON looks
 * as described, otherwise List<Object> may be better and a validation,
 * within the iteration.
 */
@SuppressWarnings("unchecked") 
final List<Map<String, String>> list = gson.fromJson("[{ ... }]", List.class);

final List<String> stringList = list.stream()
            .map(m -> m.get("rowId"))
            .collect(Collectors.toList());

System.out.println(stringList);

寫一個POJO類為

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class RootObject {

    @SerializedName("rowId")
    @Expose
    private String rowId;

    public String getRowId() {
        return rowId;
    }

    public void setRowId(String rowId) {
        this.rowId = rowId;
    }

}

然后只需創建List<RootObject>並從POJO中獲取值。

你有:

String str = "[{\"rowId\":\"03 EUR10580000\"},{\"rowId\":\"03 EUR10900001\"},{\"rowId\":\"03 EUR1053RUD*\"},{\"rowId\":\"033331\"}]"

您可以執行以下操作(不需要任何外部庫,例如gson):

str = str.replace("{\"rowId\":\"","").replace("\"}","").replace("[","").replace("]","");
List<String> rowIDs = str.split(",");

如果字符串格式為JSON,則還可以trim() rowIDs每個字符串

您需要將json字符串解析為JsonArray 然后遍歷JsonArray實例,並將每個json元素添加到列表ls 解決方案以下代碼為sinppet:

    List<String> ls = new ArrayList<String>();
    String json = "[{\"rowId\":\"03 EUR10580000\"},{\"rowId\":\"03 EUR10900001\"},{\"rowId\":\"03 EUR1053RUD*\"},{\"rowId\":\"033331\"}]";
    JsonArray ja = new JsonParser().parse(json).getAsJsonArray();

    for(int i = 0; i < ja.size(); i++) {
       ls.add(ja.get(i).getAsJsonObject().get("rowId").toString());
    }
    for(String rowId : ls) {
       System.out.println(rowId);
    }
    /* output : 
    "03 EUR10580000"
    "03 EUR10900001"
    "03 EUR1053RUD*"
    "033331" */

暫無
暫無

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

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