2

Hello I have been trying to read a JSON file in java using the json.simple library, I read more than a dozen of tutorials on how to do this but in the end the way my JSON file is written is causing me a lot of trouble.

{
"0": {
    "POI": "43df8ad6f964a520b92e1fe3",
    "latitude": 40.731356448341,
    "longitude": -73.988671302795,
    "photos": "https:\/\/irs3.4sqi.net\/img\/general\/612x612\/343235_eezF7KZ55QpdVVNuMTFOO86bikjUbmrxb1IEuf2C1uI.jpg",
    "POI_category_id": "Arts & Entertainment",
    "POI_name": "AMC Loews Village 7"
  },
  "1": {
    "POI": "4bfec352daf9c9b64038f9ef",
    "latitude": 40.75358312925,
    "longitude": -74.214450350548,
    "photos": "https:\/\/irs1.4sqi.net\/img\/general\/540x720\/c5xfqE_ajHOZb1LBtUBEdYNlc9aQ12EoPcavI_dVkDw.jpg",
    "POI_category_id": "Food",
    "POI_name": "Wendy's"
  }
...
}

My issue is that I have no idea how I can get the first value "0":, "1": without having a key next to so I could use the .get("KEY") function. I tried something like jsobj.get(i) and then increasing the value of i by one every time but that didn't work at all.

This is my first time trying to do something with json so I have no idea if what I am trying to do is right. Thanks in advance

11
  • Which library are you using? Commented May 23, 2018 at 9:47
  • If you're using the org.json library for JSON representation, you can read the entire file and store the content in a StringBuilder, and then use that StringBuilder.toString() to instantiate a new JSONObject(StringBuilder.toString()). Commented May 23, 2018 at 9:49
  • "I tried something like jsobj.get(i) and then increasing the value of i by one every time but that didn't work at all." - That should work fine, but remember i would need to be a string in this case. Can you include a minimal reproducible example so we can see what's going on? Commented May 23, 2018 at 9:49
  • org.json.simple is the library i am using @MạnhQuyếtNguyễn Commented May 23, 2018 at 9:51
  • @berry120 out of curiosity i tried that myself literally 2 mins ago and it kind of worked, yet i don't know what would be the best way for me to extract the data :/ Commented May 23, 2018 at 9:52

1 Answer 1

1

Assuming your JSON is stored in a string called json:

JSONObject obj = (JSONObject)new JSONParser().parse(json);
JSONObject ele;
for(int i=0 ; (ele=(JSONObject)obj.get(Integer.toString(i)))!=null ; i++) {
    System.out.println("Index " + i + ":");
    System.out.println(ele.get("POI"));
    System.out.println(ele.get("latitude"));
    System.out.println(ele.get("longitude"));
    ///etc.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.