import java.io.FileNotFoundException;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class testdata {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
JSONParser parser = new JSONParser();
try { System.out.println("Reading JSON file from Java program");
FileReader fileReader = new FileReader("C:\\Users\\...\\testdata.json");
JSONObject json = (JSONObject) parser.parse(fileReader);
String title = (String) json.get("Attachment__c");
System.out.println("title: " + title);
} catch (Exception ex)
{ ex.printStackTrace(); }
}}
在尝试使用上面的代码时,我收到以下错误。
java.lang.ClassCastException:org.json.simple.JSONArray无法转换为org.json.simple.JSONObject 在testdata.main(testdata.java:33)
我的JSON文件
答案 0 :(得分:1)
您可以将其解析为对象类型,然后对具有 Array 或 Object 的哪种类型的json结构进行检查>。
System.out.println("Reading JSON file from Java program");
FileReader fileReader = new FileReader("C:\\Users\\...\\testdata.json");
Object jsonObj = parser.parse(fileReader);
if (jsonObj instanceof JSONObject) {
// its an object
} else if (jsonObj instanceof JSONArray) {
JSONArray array = (JSONArray) jsonObj;
array.forEach(i -> {
JSONObject obj = (JSONObject) i;
JSONObject attributes = (JSONObject) obj.get("attributes");
System.out.println(attributes.get("Attachment__c"));
});
} else {
// something else
}
答案 1 :(得分:1)
public static void main(String[] args) throws FileNotFoundException {
JSONParser parser = new JSONParser();
try {
FileReader fileReader = new FileReader("C:\\Users\\Priya\\testdata.json");
Object jsonObj = parser.parse(fileReader);
if (jsonObj instanceof JSONObject) {
} else if (jsonObj instanceof JSONArray) {
JSONArray array = (JSONArray) jsonObj;
System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
String attachmentValue = (String) ((JSONObject) array.get(i)).get("Attachment__c");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}