How can I cast a JSONObject to a custom Java class?

后端 未结 5 757
深忆病人
深忆病人 2021-02-12 15:42

In Java (using json-simple) I have successfully parsed a JSON string which was created in JavaScript using JSON.stringify. It looks like this:

{\"teq\":14567,\"         


        
5条回答
  •  隐瞒了意图╮
    2021-02-12 16:22

    UPDATE 1/9/2018

    Some years have passed since this (now popular) question was asked. While I still agree that json-simple was my need at the time, upon reflection I think the SO community is better served by having the "checkmark" next to the Jackson solution. I am un-accepting my own answer today; Jackson is pretty great!


    I think that this decent json-simple library is the victim of poor documentation. If you don't use the JSONParser (go figure!) but instead use this JSONValue.parse() method, it all works out like so:

        //JSONParser parser = new JSONParser(); // DON'T USE THIS
        Object obj = JSONValue.parse("A JSON string - array of objects: [{},{}] - goes here");
        JSONArray arrFilings = (JSONArray)obj;
        System.out.println("We can print one this way...");
        System.out.println(arrFilings.get(5) + "\n");
    
        System.out.println("We can enumerate the whole array...");
        for(Object objFiling : arrFilings){
            System.out.println(objFiling);
        }
        System.out.println("\n");
    
        System.out.println("We can access object properties this way...");
        for(Object objFiling : arrFilings){
            JSONObject o = (JSONObject)objFiling; // MUST cast to access .get()
            MyJSObject.fyq = o.get("fyq");
        }
        System.out.println("\n");
    

    Thanks to all those who posted. Sticking with json-simple was the question and this is the only json-simple answer to-date. Jackson DOES look slick, and Amazon uses it in their SDK for Java too, sooo.... if its good enough for AWS....

提交回复
热议问题