Ammar Ammar - 4 months ago 12
Java Question

Getting the string value from a JSON array's object in Java

EDIT: I actually found the answer. I can't close the question as I am new. I was able to use Array.getString(i) to return the string value needed. Thanks for all the help.

I have JSON like this:

{
"List": [
"example1",
"example2",
"example3",
"example4"
]
}


And I am trying to get the string value of those objects without using a key. How can I do that? The
getString()
for jsonObject require a key and I don't have one.

Answer Source

I assume that you have a file :/home/user/file_001.json

the file contains this : `

{"age":34,"name":"myName","messages":["msg 1","msg 2","msg 3"]}

Now let's write a program that reads the file : /home/user/file_001.json and converts its content to a java JSONObject.

package org.xml.json;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


    public class JsonSimpleRead
    {
        @SuppressWarnings("unchecked")
        public static void main(String[] args)
        {
            JSONParser parser = new JSONParser();
            try
            {
                Object obj = parser.parse(new FileReader("/home/user/file_001.json"));
                JSONObject jsonObject = (JSONObject) obj;
                String name = (String) jsonObject.get("name");
                System.out.println(name);

                long age = (Long) jsonObject.get("age");
                System.out.println(age);

                JSONArray msg = (JSONArray) jsonObject.get("messages");
                Iterator<String> iterator = msg.iterator();
                while (iterator.hasNext())
                {
                    System.out.println(iterator.next());
                }
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (ParseException e)
            {
                e.printStackTrace();
            }
        }
    }