0

I have this Json structured file, which validates as a Json file.

I need to parse this Json data using Java code. I have tried several libraries like json.org and simple Jason but I can't quite get the values from the Json file error like invalid s

{
    "capacity": "30",
    "participants": {
        "858113": {
            "studentNum": "R1506D858113",
            "module_id": "300",
            "offer_id": "4254",
            "grade": null,
            "code": "WA"
        },
        "1007938": {
            "studentNum": "R1509D1007938",
            "module_id": "300",
            "offer_id": "4254",
            "grade": null,
            "code": "WA"
        },
        "1022146": {
            "studentNum": "R1509D1022146",
            "module_id": "300",
            "offer_id": "4254",
            "grade": null,
            "code": "WA"
        },
        "1041591": {
            "studentNum": "R1510D1041591",
            "module_id": "300",
            "offer_id": "4254",
            "grade": null,
            "code": "WA"
        },
        "1226958": {
            "studentNum": "R1601D1226958",
            "module_id": "300",
            "offer_id": "4254",
            "grade": null,
            "code": "WA"
        }
    }
}

This is the Jason file and below code using json.org

 final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray participants = obj.getJSONArray("participants");
    final int n = participants.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = participants.getJSONObject(i);
      System.out.println(person.getInt("studentNum"));

    }

Basically I need to retrieve this this information as an array.

pedrohreis
  • 1,030
  • 2
  • 14
  • 33

4 Answers4

0

Use more robust OOPs. Use a library like GSON to convert JSON to objects and then further harness Java capabilities.

GSON Maven Dependency

public class Participant {
public String studentNum;
    public String module_id;
    public String offer_id;
    public String grade;
    public String code;
}

Main object:

public class ParticipantData
{

    public String capacity;

    public Map<String, Participant> participants;
}

Now using GSON to convert JSON to object and iterate:

 Gson gson = new Gson();

        Type dataType = (new TypeToken<ParticipantData>()
        {
        }).getType();

        ParticipantData data = gson.fromJson(jsonData, dataType);

        for(String e: data.participants.keySet()) {
            System.out.printf("For participant with id %s, details are %s\n", e, data.participants.get(e));
        }
TechFree
  • 2,600
  • 1
  • 17
  • 18
-1

so I have this example using Jackson:

compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.9'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.9'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.9'

Models:

public class ParticipantData {
    private String capacity;
    private Map<String, Student> participants;

    public String getCapacity() {
        return capacity;
    }

    public Map<String, Student> getParticipants() {
        return participants;
    }
}

public class Student {
    private String studentNum;
    private String module_id;
    private String offer_id;
    private String grade;
    private String code;

    public String getStudentNum() {
        return studentNum;
    }

    public String getModule_id() {
        return module_id;
    }

    public String getOffer_id() {
        return offer_id;
    }

    public String getGrade() {
        return grade;
    }

    public String getCode() {
        return code;
    }
    @Override
    public String toString() {
        return "Student{" +
                "studentNum='" + studentNum + '\'' +
                ", module_id='" + module_id + '\'' +
                ", offer_id='" + offer_id + '\'' +
                ", grade='" + grade + '\'' +
                ", code='" + code + '\'' +
                '}';
    }
}

Here it is the parser class, making use of the ObjectMapper:

import com.fasterxml.jackson.databind.ObjectMapper;
import model.ParticipantData;

import java.io.IOException;
import java.util.Optional;

public class MyJsonReader {

    private static Optional<ParticipantData> read(String jsonToParse) {
        try {
            return Optional.of(new ObjectMapper().readValue(jsonToParse, ParticipantData.class));
        } catch (IOException e) {
            e.printStackTrace();
            return Optional.empty();
       }
    }

    public static void main(String[] args) {
        String jsonToParse = getYourJsonToParseAsString();

        read(jsonToParse).ifPresent(participantData -> {
            System.out.println(participantData.getCapacity());
            participantData.getParticipants().forEach((key, value) -> {
                System.out.println(key);
                System.out.println(value);
            });
        });
    }
}

In this example, it is iterating through all the participants and printing it.

Brother
  • 2,150
  • 1
  • 20
  • 24
-1

You could use Jackson. It is easy and handles all the logic for you returning a Map with key-values.

Map<String, Object> jsonMap = new ObjectMapper().readValue(stringResponseBody, new TypeReference<Map<String, Object>>() {});
h4t0n
  • 91
  • 1
  • 9
-1

Your Code Changes using org.json

        JSONObject jsonObj = new JSONObject(JSON_DATA);

        // here participants is jsonObject, not jsonArray
        JSONObject participants = jsonObj.getJSONObject("participants");

        // this jsonObject participants has five key-value pairs.
        // so iterate through keys and fetch values (These values are also another
        // jsonObject)
        Iterator<String> key = participants.keys();
        while (key.hasNext()) {
            JSONObject person = participants.getJSONObject(key.next());
           // value of key studentNum is string type
            System.out.println(person.getString("studentNum"));
        }
Nitika Bansal
  • 740
  • 5
  • 10