![](/img/trans.png)
[英]How to get the values of a JSONArray by using simple JSON in Java?
[英]Java get values from json file using simple json lib
我有這種格式的 json 文件:
{
"1": {
"path": ["C"],
"Des": ["D"]
},
"2": {
"path": ["A"],
"Des": ["D"]
},
"3": {
"path": ["C"],
"Des": ["B"]
}
}
我想在 class 對象中獲取值,並在將其添加到 arraylist 對象之前使用此代碼查看結果
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class test2 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/dell/Desktop/streams.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject json0 = (JSONObject) jsonObject.get(0);
System.out.println(json0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
問題是jsonObject
不是數組,嘗試這樣做:
jsonObject.get("1")
而不是這個:
jsonObject.get(0)
要獲取 json object 的所有密鑰,只需執行以下操作:
jsonObject.keySet()
如果要將鍵放入列表:
List<String> keys = new ArrayList<>((Set<String>) jsonObject.keySet());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.