1

I know that this question was already asked, i tried all solutions but nothing works for me. So i have this json syntax string:

{
   tasks: [
      {
         blockId: "startpoint1",
         properties: [ "aaaa"  ]
      },
      {
         blockId: "endpoint2",
         properties: [ "tttttt" ]
      } 
   ]
}

I tried to create a JSONObject from this String by this way:

JSONParser parser=new JSONParser();
try {
    JSONObject json=(JSONObject) parser.parse(req.getParameter(WORKFLOW_DEFINITION_PROPERTIES));
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

Now i want to loop on the tasks array to get every element blockId. I tried to do this by casting the JSONObject to JSONArray like this:

JSONArray tasks=(JSONArray) json.get("tasks");

but i still enable to loop over tasks to get the blockId's. Can you tell me what i made wrong or how to fix this?

2
  • var obj = JSON.parse(string); Commented Aug 22, 2017 at 12:54
  • I'm in Java no javaScript Commented Aug 22, 2017 at 12:55

3 Answers 3

4

You have to use getJsonArray method instead of get method to retrieve the array of tasks :

JSONArray tasks= json.getJsonArray("tasks");
Sign up to request clarification or add additional context in comments.

1 Comment

This method is not included in org.json.simple.JSONArray class i use
1

Just change the way you create your JSONObject.

JSONObject jObject = new JSONObject(jsonStr);
//later you can access to your array 
JSONArray tasks=(JSONArray) jObject.get("tasks");

2 Comments

The constructor of JSONObject is JSONObject(map), so i can't create a JSONObject directly with a String
Thats not true, with the version <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency> you can create an object from a string.
-1

Do you need this?

    var arrayVariable=[
      {
         blockId: "startpoint1",
         properties: [ "aaaa"  ]
      },
      {
         blockId: "endpoint2",
         properties: [ "tttttt" ]
      } 
   ]

    arrayVariable.map(function(d){
       return d.blockId
       });

Out put you will get all you blockId as

     ["startpoint1", "endpoint2"]

2 Comments

No, my json string is created dynamically from an UI diagram so, i can't create it statically like you done
So,Convert you JSON string to JSON Object using JSON.parse(JSONstring) and then use my above method it will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.