简体   繁体   中英

How to return a single object with json-simple in java?

I've this json object:

public static final String JSON_TEXT = "{" +
"\"Subjects\": [{" +
            "\"primaryKey\": \"1\"," +
            "\"subjectName\": \"English\"" +
        "}," +
        "{" +
            "\"primaryKey\": \"2\"," +
            "\"subjectName\": \"Spanish\"" +
        "}" +
    "]," +
    "\"Exams\": [{" +
            "\"primaryKey\": \"1\"," +
            "\"grade\": \"10\"" +
        "}," +
        "{" +
            "\"primaryKey\": \"2\"," +
            "\"grade\": \"20\"" +
        "}" +
    "]" +
"}";

and need to build some methods for a json dao implementation.

I've built

public Collection<Subject> getSubjects()

successfully but I got totally stuck with

public Subject findSubjectById(Integer subjectId)

This was my first idea so far:

public Subject findSubjectById(Integer subjectId) {
    JSONObject obj = (JSONObject)JSON_PARSER.parse(JSON_TEXT);
    if (obj.get(subjectId) != null)
        try {
            JSONArray subjectsArray = (JSONArray) obj.get("Subjects");

            for (int i = 0; i < subjectsArray.length(); i++){   

            }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
        return subject;

} 

Any ideas/ examples are highly appreciated to solve this. Thanks in advance!

Try this in your for loop

JSONObject subDtl=subjectsArray.getJSONObject(i);
int subKey=subDtl.getInt("primaryKey"); 
String subName=subDtl.getString("subjectName");

I know you don't use Gson but it would resolve all your issues. Also I recommend to change field names to "subjects" and "exams" instead of "Subjects" and "Exams".

Here is the complete solution that is at least worth to be considered.

public class Data {

    private List<Subject> subjects;

    private List<Exam> exams;

    public Data(String json) {
        Data data = new Gson().fromJson(json, Data.class);
        this.subjects = data.subjects;
        this.exams = data.exams;
        Reporter.log(new Gson().toJson(this), true);
    }

    public Subject findSubjectById(Integer id) {
        return subjects.stream().filter(subject -> subject.primaryKey.equals(id)).findAny().orElse(null);
    }

    public Exam findExamById(Integer id) {
        return exams.stream().filter(exam -> exam.primaryKey.equals(id)).findAny().orElse(null);
    }

    public List<Subject> getSubjects() {
        return subjects;
    }

    public void setSubjects(List<Subject> subjects) {
        this.subjects = subjects;
    }

    public List<Exam> getExams() {
        return exams;
    }

    public void setExams(List<Exam> exams) {
        this.exams = exams;
    }

    public class Subject {
        private Integer primaryKey;
        private String subjectName;

        public Integer getPrimaryKey() {
            return primaryKey;
        }

        public void setPrimaryKey(Integer primaryKey) {
            this.primaryKey = primaryKey;
        }

        public String getSubjectName() {
            return subjectName;
        }

        public void setSubjectName(String subjectName) {
            this.subjectName = subjectName;
        }
    }

    public class Exam {
        private Integer primaryKey;
        private String grade;

        public Integer getPrimaryKey() {
            return primaryKey;
        }

        public void setPrimaryKey(Integer primaryKey) {
            this.primaryKey = primaryKey;
        }

        public String getGrade() {
            return grade;
        }

        public void setGrade(String grade) {
            this.grade = grade;
        }
    }

}

Here are tests that verify our solution

@SpringBootTest(classes = TestNGWithSpringApplication.class)
public class JsonDataIT extends AbstractTestNGSpringContextTests {

    String json = "{  \n"
            + "   \"subjects\":[  \n"
            + "      {  \n"
            + "         \"primaryKey\":\"1\",\n"
            + "         \"subjectName\":\"English\"\n"
            + "      },\n"
            + "      {  \n"
            + "         \"primaryKey\":\"2\",\n"
            + "         \"subjectName\":\"Spanish\"\n"
            + "      }\n"
            + "   ],\n"
            + "   \"exams\":[  \n"
            + "      {  \n"
            + "         \"primaryKey\":\"1\",\n"
            + "         \"grade\":\"10\"\n"
            + "      },\n"
            + "      {  \n"
            + "         \"primaryKey\":\"2\",\n"
            + "         \"grade\":\"20\"\n"
            + "      }\n"
            + "   ]\n"
            + "}";

    @Test
    public void findSubjectTest() {
        Data.Subject subject = new Data(json).findSubjectById(new Integer(2));
        Assert.assertEquals(subject.getSubjectName(), "Spanish");
    }

    @Test
    public void findExamTest() {
        Data.Exam exam = new Data(json).findExamById(new Integer(2));
        Assert.assertEquals(exam.getGrade(), "20");
    }

}

That should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM