luillyyyy / json-simple

Automatically exported from code.google.com/p/json-simple
1 stars 0 forks source link

Issue when parsing #1

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Hi when I run the following
        jsonData = NetUtils.getHTTPFile("http://www.iobridge.com/api/feed/key=" + feedKey);
        JSONParser parser = new JSONParser();
        Object obj = null;
            //parse the JSON data
        try {
               obj = parser.parse(jsonData);
        } catch (ParseException e) {}
              JSONArray array=(JSONArray)obj;
              System.out.println(array.get(1));
              JSONObject obj2=(JSONObject)array.get(1);
              System.out.println(obj2.get("1"));

I get the following Exception
Exception in thread "main" java.lang.ClassCastException: 
org.json.simple.JSONObject
        at IOB.IOBModule.<init>(IOBModule.java:33)
        at myroomcontrol.Main.main(Main.java:30)
Java Result: 1

Original issue reported on code.google.com by callum.j...@gmail.com on 17 Feb 2009 at 9:31

GoogleCodeExporter commented 8 years ago
What is the value of feedKey when you get the exception? I pass "123"
(http://www.iobridge.com/api/feed/key=123) and get the result:
{{{
{
        "module": {
            "serial": "",
            "label": "",
            "lat": "",
            "long": "",
            "location": "",
            "datetime": "Feb-17-2009 06:44:25 AM",
            "status": "Offline",
            "channels": [
           ]

        }}
}}}

It seems that the top level entity is a JSON object, not a JSON array.

Original comment by fangyid...@gmail.com on 17 Feb 2009 at 11:53

GoogleCodeExporter commented 8 years ago
Hey thanks for the reply.
Setting it to cast as a JSONObject works well.

I am somewhat new to parsing and handling JSON in Java, do you know of any good 
tutorials how I could access 
say the array of channels or even the status?

Thanks,
Callum

Original comment by callum.j...@gmail.com on 18 Feb 2009 at 4:01

GoogleCodeExporter commented 8 years ago
JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can 
access it
with standard operations of Map or List:

JSONObject obj = (JSONObject) parser.parse(jsonData);
JSONObject module = (JSONObject) obj.get("module");
JSONArray channels = (JSONArray) module.get("channels");

Please refer
http://code.google.com/p/json-simple/wiki/MappingBetweenJSONAndJavaEntities for
mapping of entities. You can also join the discussion group
(http://groups.google.com/group/json-simple) if you have further questions on 
using
JSON.simple.

Original comment by fangyid...@gmail.com on 18 Feb 2009 at 4:47