我試圖解析一些JSON(以下節選),但我收到以下錯誤:我該如何解析這種類型的JSON? (只能遍歷數組或java.lang.Iterable的實例)
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Can only iterate over an array or an instance of java.lang.Iterable
而一個摘錄非常大的json文件:
[
{
"normal" : "Le tour change de sens ! Ce n'est pas une action, c'est le joker!"
},
{
"normal" : "Prends la main de ton voisin de gauche"
},
{
"normal" : "Fais une déclaration d'amour à la personne en face de toi!"
},
{
"normal" : "Reste sur les genoux de la personne à ta droite pendant un tour"
},
自己找出來。下面的代碼:
import org.json.simple.JSONArray;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ParseJson{
static String printAcounts = "";
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException, JSONException{
JSONParser parser = new JSONParser();
JSONArray objArray = (JSONArray) parser.parse(new FileReader("C:\\Users\\Bogdanel\\Desktop\\Ressources\\normal_actions.json"));
for (Object o : objArray){
JSONObject obj = (JSONObject) o;
String s = (String) obj.get("normal");
System.out.println(s);
}
}
}
ascasccascascasc
您使用哪個JSON庫? – hexafraction
您所擁有的'JSONArray'類沒有實現'Iterable',因此您不能使用Java的擴展for-loop語法。解決方案將使用'JSONArray'上的方法。例如,如果它有長度或大小或計數和get方法。這將取決於你正在使用的是哪個json庫。 – dsh