java - 检索 JSON 对象

标签 java json

下面我附上了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/

相关文章:

java.lang.NullPointerException at org.apache.jsp.page_jsp._jspInit 在 Tomcat 6 中,但在 Tomcat 7 中有效

java - 为什么set不允许重复值,它们背后使用了什么样的机制?

java - Android 上的 JNI : How to retrieve a string from Java code?

Linux 和 Windows 之间的 Java 内存使用差异

java - 未找到小程序类

javascript - JSON 字符串到多维数组

java - 如何将具有复合键的键值结构映射到 Java 中的 json 对象

c++ - JsonCpp 写回 Json 文件

javascript - JSON 发送空数组

javascript - 带有 Angularjs 的 json 表