Json使用Java解析文件

时间:2019-06-10 07:56:32

标签: java json

我有这个Json结构文件,它可以作为Json文件进行验证。

我需要使用Java代码解析此Json数据。我尝试了一些库,例如json.org和简单的Jason,但无法完全从Json文件错误中获取值,例如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"
        }
    }
}

这是Jason文件,下面是使用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"));

    }

基本上,我需要以数组的形式检索此信息。

4 个答案:

答案 0 :(得分:0)

使用更强大的OOP。使用GSON之类的库将JSON转换为对象,然后进一步利用Java功能。

GSON Maven Dependency

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

主要对象:

public class ParticipantData
{

    public String capacity;

    public Map<String, Participant> participants;
}

现在使用GSON将JSON转换为对象并进行迭代:

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

答案 1 :(得分:-1)

所以我有使用杰克逊的例子:

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'

型号:

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 + '\'' +
                '}';
    }
}

这里是使用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);
            });
        });
    }
}

在此示例中,它遍历所有参与者并进行打印。

答案 2 :(得分:-1)

您可以使用Jackson。这很容易,可以处理您返回带有键值的Map的所有逻辑。

Map<String, Object> jsonMap = new ObjectMapper().readValue(stringResponseBody, new TypeReference<Map<String, Object>>() {});

答案 3 :(得分:-1)

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