0

I have the following string value:

'[
   {
      "fruit":"apple",
      "color":"green"
   },
   {
      "fruit":"banana",
      "color":"yellow"
   },
   {
      "fruit":"lime",
      "color":"green"
   },
   {
      "fruit":"peach",
      "color":"pink"
   }
]'

which I like to convert back to a json object in java but I have no clue how to achieve this.

Anyone who can guide me?

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
Malin
  • 697
  • 5
  • 21
  • 1
    How did you convert it to a string in the first place? I'm sure whatever library you used (which you may want to specify) has a method of doing the reverse operation. – Federico klez Culloca Aug 18 '21 at 09:10
  • I have an arraylist with json objects, I am not sure the provided examples will answer my question. I have to check. – Malin Aug 18 '21 at 09:37

1 Answers1

1

You can use json-simple open-source library for JSON parsing and formatting. Download from net and add java build path classpath.

import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


public class Main {

  

  public static void main(String[] args) {
      String jsonString = "[{\"fruit\":\"apple\",\"color\":\"green\"},{\"fruit\":\"banana\",\"color\":\"yellow\"}]";
      JSONParser parser = new JSONParser();
      JSONArray obj;
      try {
         obj = (JSONArray)parser.parse(jsonString);
         System.out.println(obj.get(0));
      } catch(ParseException e) {
         e.printStackTrace();
      }
   }

}
Iceberg
  • 21
  • 5