下面我附上了Java代码,首先我将“图像”结果检索为“{“jpg”:“JPEG文件”,“gif”:“GIF文件”,“png”:“PNG文件”}“
使用结果,尝试获取“jpg”节点,无法检索数据,而是收到错误,因为 java.lang.String 无法转换为 org.json.simple.JSONObject
我喜欢拍摄图像,然后是jpg。不是直接JPG值
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JSONDemo {
public static void main(String[] args) {
try{
String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}";
JSONObject jobject=new JSONObject();
JSONParser jparser=new JSONParser();
jobject = (JSONObject) jparser.parse(jsonfile);
jobject=(JSONObject) jobject.get("images");
System.out.println(jobject);
System.out.println(jobject.getClass().getName());
jobject=(JSONObject) jobject.get("jpg");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
最佳答案
这里的错误是“jpg”不是一个JSONObject
,而是一个具有关联值“JPEG file”
的键,它是一个简单的字符串。这就是为什么你会收到这样的错误。
为了检索与键 jpg
关联的值,请阅读以下代码。我添加了一些注释来帮助您理解每个步骤,但请随时询问更多详细信息。
String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}";
JSONObject jobject = new JSONObject();
JSONParser jparser = new JSONParser();
//Convert your string jsonfile into a JSONObject
try {
jobject = (JSONObject) jparser.parse(jsonfile);
} catch (ParseException ex) {
Logger.getLogger(Josimarleewords.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(jobject.toString());
//{"Address":"Chennai","name":"Raj","images":{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"}}
//Get the node image, and convert it into a JSONObject
//You're able to do so, because the value associated to "images"
//is in json format.
jobject=(JSONObject) jobject.get("images");
System.out.println(jobject.toString());
//{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"}
//Retrieves the value associated to the key jpg.
//The value here is not in json format, it is a simple string
String jpg = (String)jobject.get("jpg");
System.out.println(jpg.toString());
//JPEG file
关于java - 检索 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45277827/