下面我附上了Java代码,首先我要检索"图像"结果为" {" jpg":" JPEG文件"," gif":" GIF文件",&# 34; png":" PNG文件"} "
使用结果,试图获得" jpg"节点,无法检索数据,而是我收到错误java.lang.String cannot be cast to 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());
}
}
}
答案 0 :(得分:0)
这里的错误是“jpg”不是JSONObject
,而是具有关联值"JPEG file"
的密钥,它是一个简单的字符串。这就是你得到这样的错误的原因。
在ordre中检索与键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