LookIntoEast
LookIntoEast

Reputation: 8798

How to parse complicated json string in Java

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

Upvotes: 0

Views: 66

Answers (2)

Mateo Barahona
Mateo Barahona

Reputation: 1391

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

Upvotes: 1

mfaisalhyder
mfaisalhyder

Reputation: 2284

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'

Upvotes: 1

Related Questions