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?

2
  • 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. Commented Aug 18, 2021 at 9:10
  • I have an arraylist with json objects, I am not sure the provided examples will answer my question. I have to check. Commented Aug 18, 2021 at 9:37

1 Answer 1

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();
      }
   }

}
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.