[英]Store JSON object as a string and print each value in java
我有一個長度未知的 JSON 對象{"name":["123-abc","234-bca","567-yuio"]}
。 我需要將它存儲為字符串並拆分逗號並迭代以僅打印值,即 123-abc 應首先打印,然后 234-bca 等。 -> 輸入: {"name":["123-abc","234-bca","567-yuio"]}
-> 輸出: 123-abc 234-bca 567-yuio
請幫助我,因為我是編碼新手。 謝謝你
你可以試試這個:
JSONObject json = (JSONObject) object;
String input = json.get("name");
//String input = "\"123-abc\",\"234-bca\",\"567-yuio\"";
String[] strArray = input.split(",");
for (String string : strArray)
System.out.println(string.replace("\"", ""));
這里的對象是您存儲 JSON 對象的地方。
首先,您必須在逗號處拆分字符串,並且必須使用例如 for 循環遍歷拆分列表:
for (String val : input.substring(1, input.length() - 1).split(",")) {
System.out.println(val.replace("\"", ""));
}
您不需要將它存儲為字符串,您實際上可以從 JSON 對象中提取該數組並對其進行迭代。
JSON obj = new JSONObject(); //Get/store your data however you'd like. I will call it obj
String[] name = obj.get( "name" );
for (int i = 0; i < name.length; i++) { //Loop through your array and output each part
System.out.println( name[ i ] );
}
如果您需要將obj
轉換為字符串,可以使用.toString()
函數。 但以上應該是輸出該數據的最簡單方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.