You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java测验应用如何将用户答案写入对应JSON对象的键值空位

实现方案

你可以使用Java常用的JSON处理库Jackson完成需求,步骤如下:

前置依赖

如果使用Maven管理项目,在pom.xml中引入Jackson依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

如果是Gradle项目则引入对应配置即可。

核心实现代码

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public void writeAnswersToJson(ArrayList<String> userAnswers, String jsonFilePath) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    // 读取原JSON文件为List<Map>结构,每个Map对应数组中的一个{"Qx":""}对象
    List<Map<String, String>> answerList = objectMapper.readValue(
            new File(jsonFilePath),
            new TypeReference<List<Map<String, String>>>() {}
    );

    // 遍历答案填充,避免用户中途退出导致的索引越界
    int fillSize = Math.min(userAnswers.size(), answerList.size());
    for (int i = 0; i < fillSize; i++) {
        Map<String, String> questionEntry = answerList.get(i);
        // 每个Map只有一个key即Qx,直接取第一个key替换值
        String questionKey = questionEntry.keySet().iterator().next();
        questionEntry.put(questionKey, userAnswers.get(i));
    }

    // 格式化写回JSON文件
    objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(jsonFilePath), answerList);
}

调用示例

在你获取到用户答案后直接调用上述方法即可:

public void mainProcess() {
    try {
        ArrayList<String> userAnswers = askQuestionsOneByOne();
        // 替换为你实际的JSON文件路径
        String jsonPath = "你的文件路径/answer_template.json";
        writeAnswersToJson(userAnswers, jsonPath);
    } catch (IOException e) {
        // 自定义异常处理逻辑,比如打印日志、提示用户
        e.printStackTrace();
    }
}

可选优化建议

你当前的JSON结构是每个题目单独作为一个对象放在数组里,如果你可以调整JSON结构,建议简化为单个对象,操作效率更高:

{
  "Q1": "",
  "Q2": "",
  ...
  "Q15": ""
}

对应填充逻辑可以直接按key赋值,不需要遍历数组匹配。

内容的提问来源于stack exchange,提问作者Adwait Kulkarni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:57:03