简体   繁体   English

如何在Java中使用json-simple返回单个对象?

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

I've this json object: 我有这个json对象:

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. 并且需要为json dao实现构建一些方法。

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 在您的for循环中尝试

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. 我知道您不使用Gson,但可以解决所有问题。 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 那应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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