简体   繁体   English

从ResultSet用Java创建嵌套的json

[英]Create nested json with java from ResultSet

I'm working to create a web service to return one nested json like this: 我正在努力创建一个Web服务来返回一个嵌套的json,如下所示:

{
    "questionaire": {
        "idSection": 1,
        "sectionName": "Section Test 1",
        "questions": {
            "text": {
                "idQuestion": 1,
                "statement": "Question statement",
                "kindQuestion": "boolean",
                "availableAnswers": {
                    "idAnswer": 1,
                    "stringAnswer": "answer 1"
                }
            }
        }
    },
    "idSection": 1,
    "sectionName": "Section Test 1",
    "questions": {
        "text": {
            "idQuestion": 1,
            "statement": "Question statement",
            "kindQuestion": "boolean",
            "availableAnswers": {
                "idAnswer": 1,
                "stringAnswer": "answer 1"
            }
        }
    }
}

I'm not 100% sure if the structure I wrote is correct, the idea is: I got sections, which contains questions and every answer related to question is from one kind (boolean, numeric, select) and has her own answers. 我不是100%肯定我编写的结构是否正确,但是我的想法是:我得到了包含问题的部分,并且与问题相关的每个答案都来自一种(布尔,数字,选择)并有自己的答案。 All this data I have it on a database, now I have to get the sections and all the relative information like: section > questions > type answer > available answers. 所有这些数据我都保存在数据库中,现在我必须获取这些部分以及所有相关信息,例如:部分>问题>输入答案>可用答案。

This is what I'm trying to do but it doesn't work appropriately I don't know how to nest the questions relative to the section and the answers inside the questions and go on. 这是我要尝试执行的操作,但无法正常工作,我不知道如何嵌套与本节相关的问题以及问题中的答案,然后继续。

// ques is a JSONArray    
sections = resultset from database;
              // While loop for every section
              while(sections.next()){
                 // Here I start to create the json
                 jsonD.put("sectionID", sections.getInt("id"));
                 jsonD.put("sectionName", sections.getString("sectionName"));
                 questions = resultset from database, contains the questions for every section
                 // Recupera preguntes vinculades a la seccio
                 while(questions.next()){
                     ques.put("idQuestion", id);
                     ques.put("statement", statement);
                     ...
                 }

              }

On this point my code does not create the nested json appropriately 关于这一点,我的代码无法正确创建嵌套的json

You have to create a hierarchical data structure and then convert it into Json. 您必须创建一个分层数据结构,然后将其转换为Json。 Represent tree hierarchy in java 在Java中表示树层次结构

Try using the jackson API to generate JSON https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/ 尝试使用jackson API生成JSON https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

Take a look at JsonObjectBuilder, JsonArrayBuilder, etc. in javax.json. 看看javax.json中的JsonObjectBuilder,JsonArrayBuilder等。 They will do the trick for you. 他们将为您解决问题。

Google gson are much more advanced when it comes to build multi dimentional json structures. Google gson在构建多维json结构时要先进得多。 First create an data heirarchy something like the below code. 首先创建一个数据层次结构,类似于下面的代码。 Then based on the data you have, set the the values to each of the fields in the Class. 然后根据您拥有的数据,将值设置为“类”中的每个字段。 public class CreateGoalRequest { 公共类CreateGoalRequest {

@SerializedName("name")
private String goalName;

@SerializedName("recommendable_modules_alt")
private RecommendationModuleAlt recommendationList;

@SerializedName("target_modules")
private List<TargetModule> targetModules;

@SerializedName("max_recommendation_size")
private int recommendationSize;

@SerializedName("start_date")
private String startDate;

@SerializedName("metrics_enabled")
private Boolean metricsEnabled;

public List<TargetModule> getTargetModules() {
    return targetModules;
}

....... .......

And constuct your heirarchy using 并使用

import com.google.gson.Gson;
            CreateGoalRequest createGoalRequest = new CreateGoalRequest();
            createGoalRequest.setGoalName(goalName);
            createGoalRequest.setMetricsEnabled(Boolean.TRUE);
            createGoalRequest.setTargetModules(targetModules);
            createGoalRequest.setRecommendationList(recommendableList);
            createGoalRequest.setRecommendationSize(recommendableItemCount);
            createGoalRequest.setStartDate(startDate);

            try {
                String entity = new String(gson.toJson(createGoalRequest));

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

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