-2

I am trying to parse a json string to java but have got stuck. My code looks like the below.

public static void main(String args[]) throws FileNotFoundException, IOException, ParseException {


    // parsing file "JSONExample.json" 
       Object obj = new JSONParser().parse(new FileReader("teams.json")); 

    // typecasting obj to JSONObject 
       JSONObject jo = (JSONObject) obj; 


    // getting address 
       Map teams = ((Map)jo.get("api")); 

       // iterating address Map 
       Iterator<Map.Entry> itr1 = teams.entrySet().iterator(); 
       while (itr1.hasNext()) { 
           Map.Entry pair = itr1.next(); 


           System.out.println(pair.getKey() + " : " + pair.getValue()); 
       } 

And I get the following result.

    teams : [{"arena":"Old Trafford","name":"Manchester United","team_id":33,"city":"Manchester"}]
    results : 1

My teams.json looks like following

    {
        "api": {
            "results": 1,
            "teams": [
                {
                    "team_id": 33,
                    "name": "Manchester United",
                    "arena": "Old Trafford",
                    "city": "Manchester",
                }
            ]
        }
    }

How do I continue if I just want the keys and values in the teams-array into an arraylist in java for example.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
JavaNisse
  • 17
  • 5
  • Your code does not appear to match the output, suggesting that other code is producing the output, not what you are showing. Please create and post a valid [mre] with your question and show its output to avoid confusion. – Hovercraft Full Of Eels Feb 29 '20 at 13:04
  • the question could do with tagging which of the many JSON parsers you are using. There's several candidates that use `JSONParser`. – Tom Hawtin - tackline Feb 29 '20 at 13:06
  • check out https://www.baeldung.com/jackson-nested-values or http://tutorials.jenkov.com/java-json/jackson-jsonnode.html – hovanessyan Feb 29 '20 at 13:06
  • @TomHawtin-tackline, true. There are a lot of different JSONParser. I used json-simple which I have read are not really updated for a while and I should perhaps use jackson instead but I solved it now. The problem I had were how to iterate over teams but found a solution. – JavaNisse Feb 29 '20 at 14:01
  • @hovanessyan thank you for the pages. I got some ideas from them I suddenly found I similar example that helped me. – JavaNisse Feb 29 '20 at 14:05
  • @HovercraftFullOfEels the code does match the output. I know since I got it to work. But I will have in mind for next time to post a valid minimal repoducible example. – JavaNisse Feb 29 '20 at 14:05

1 Answers1

0

you can use GSON library of google. Let's try this example.

  1. First create your java Bean (FootballPlayer.java)

    FootballPlayer.java

  2. Then you can parse your JSON to Array:

    ReadJson1.java

Credits to: Github@RicardoMoya

Capriatto
  • 947
  • 1
  • 8
  • 17