0

For the json string like below, I'd like to iterate over the DayOrder 2 and 3, how can I parse?

{
  "data": [
    {
      "DayOrder": 2,
      "DayOfWeekStr": "Tuesday"
    },
    {
      "DayOrder": 3,
      "DayOfWeekStr": "Wednesday"
    }
  ]
}

The code I've tried is like:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;


 JSONParser jsonParser = new JSONParser();
 Object obj = jsonParser.parse(inputstring);
 JSONArray array = (JSONArray) obj["data"];

And I've tried a lot others but not work

1
  • Insert the code you already tried. There are so many JSON parsers for JAVA we need to know which one you use Commented Jul 3, 2021 at 7:37

2 Answers 2

1

You can try something like this;

String jsonString = "{\"data\":[{\"DayOrder\":2,\"DayOfWeekStr\":\"Tuesday\"},{\"DayOrder\":3,\"DayOfWeekStr\":\"Wednesday\"}]}";

Use Gson

Gson gson = new Gson();
YourDTO dtoObj = gson.fromJson(jsonString, YourDTO.class);
// dtoObj.getData().stream()....
dtoObj.getData().forEach(obj -> {
    // your code goes here
    }
);

Import gson like this;

Add this in pom.xml for maven based project:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.7</version>
</dependency>

Add this in build.gradle for gradle based project:

implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'
Sign up to request clarification or add additional context in comments.

1 Comment

one question, how can I import gson?
1

While Gson is clearly nice, you could as well just use org.json properly as you already have it as we can see

Something like

String jsonData = "{\"data\": [ {   \"DayOrder\": 2,   \"DayOfWeekStr\": \"Tuesday\" }, {   \"DayOrder\": 3,   \"DayOfWeekStr\": \"Wednesday\" }]}";

final JSONObject obj = new JSONObject(jsonData);
final JSONArray data = obj.getJSONArray("data");
for(int i  = 0; i < data.length(); i++) {
   JSONObject dataObj = data.getJSONObject(i);
   LOG.info("DayOrder {}", dataObj.getInt("DayOrder"));
}

Comments

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.