简体   繁体   中英

Parsing JSONObject in Java to access its keys

I am new to java so sorry if my question is primitive, I have a json like :

and I want to iterate based on number of items in JSONObject:

public static void main(String[] args, int value)
{
    JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader("/Users/.../Documents/workspace/changeReturn/bin/availableCash.json"));


            for (int n=0; n < ((String) obj).length(); n++)
            {
                ...
            }

        }

}

How can I get the value of obj element eg "2" for "$100" or "5" for "$50" and save it in objValue so that I can continue my operation listed in the code above.

There is a library for this!

JSON in Java

The library here allows us to take a JSON object, read it from an InputStream and access it.

You can download that library here

Hopefully this helps you out, I am not sure exactly what you are trying to do.

Example:

                JSONObject obj = new ("{\n" +
"    \"$100\":\"2\",\n" +
"    \"$50\":\"5\",\n" +
"    \"$30\":\"3\",\n" +
"    \"$10\":\"8\",\n" +
"    \"$5\":\"4\",\n" +
"}");
obj.get("$100"); //returns 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM