0

I've been searching all over the internet for a solution to my problem, but i am very new to Java and have not been able to find an answer that I can understand

I am trying to read a JSON object from a url, lets say it's called http://www.example.com/abc.html , and on that url I have the following JSON code

{ "articles":[ { "title":"example title" , "content":"example content"} ] } 

I want to be able to get the value of title into a variable.

I have not been able to figure out how to use any of the common JSON parsing libraries and none of my code has worked so far.

Thanks in advance to anyone who can help with either posting some code that has worked for them or maybe posting a link to simple tutorial (however I have not been able to find any simple ones)

4
  • Look at the examples here oracle.com/technetwork/articles/java/json-1973242.html Commented Jul 20, 2014 at 17:26
  • Just in case you are looking for the library jar (as I did) you can find it here: java2s.com/Code/JarDownload/java-json/java-json.jar.zip Commented Jul 20, 2014 at 17:38
  • @GameDroids would you be able to tell me what I should do with that file? Commented Jul 20, 2014 at 17:47
  • @user3858355: unzip the java-json.jar and copy it in your project directory. Now you can add it to your project as a library. This can either be done with your IDE (NetBeans, Eclipse) which is really easy: right click on your projects folder and choose "properties" > "Libraries" > "add Jar". Or you can compile your Javap-Program in the command line by using the "-cp" option like this: javac -cp ".;java-json.jar" MyProgram.java. The goal is to tell Java where to find the new JSON classes from the library (e.g. JSONArray, JSONObject... Commented Jul 20, 2014 at 18:05

1 Answer 1

1

There are lots of JSON libraries available. You could use org.json

Here's a simple code that might be able to help you, assuming you read the JSON from the web as a string.

String s = "{ \"articles\":[{ \"title\":\"example title\" , \"content\":\"example content\"}]}"; JSONObject jsonObject = new JSONObject(s); JSONArray articles = (JSONArray) jsonObject.get("articles"); JSONObject article = (JSONObject) (articles.get(0)); System.out.println(article.get("title")); // prints out example title 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.