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

Spring程序开发求助:实现JSON字符串(键值对)输入输出更新功能

Great question! Let's walk through building a Spring Boot application that takes a JSON string as input, modifies it, and returns the updated JSON string. Here's a complete, working example:

Step 1: Set Up the Spring Boot Project

You can use Spring Initializr to generate a new project with the Spring Web dependency (this includes Jackson for JSON processing out of the box). If you're using Maven, your pom.xml will include this core dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 2: Create the REST Controller

We’ll build a controller that accepts a POST request with a raw JSON string, parses it into a manipulable format, applies updates, and converts it back to a JSON string for the response. We’ll use Jackson’s ObjectMapper (auto-configured by Spring) for JSON handling:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

@RestController
public class JsonUpdateController {

    private final ObjectMapper objectMapper;

    // Inject Spring's pre-configured ObjectMapper
    public JsonUpdateController(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @PostMapping("/update-json")
    public String updateJson(@RequestBody String inputJson) throws JsonProcessingException {
        // 1. Parse input JSON string into a mutable Map
        Map<String, Object> jsonData = objectMapper.readValue(inputJson, Map.class);

        // 2. Apply your custom update logic (modify this to fit your needs)
        // Example: Add a timestamp for when the update happened
        jsonData.put("lastUpdated", System.currentTimeMillis());
        // Example: Update an existing value if the key exists
        if (jsonData.containsKey("status")) {
            jsonData.put("status", "processed");
        }
        // Example: Remove a temporary key if present
        jsonData.remove("draft");

        // 3. Convert the updated Map back to a JSON string
        return objectMapper.writeValueAsString(jsonData);
    }
}

Step 3: Customize the Update Logic

The example above includes basic modifications, but you can tailor this to your specific requirements:

  • Update fields based on business rules (e.g., increment a counter, format a date)
  • Validate input values before making changes
  • Add nested objects or arrays to the JSON structure
  • Handle different data types (strings, numbers, booleans) safely

Step 4: Test the Endpoint

You can test this endpoint using curl, Postman, or any HTTP client. Here’s a curl example:

curl -X POST http://localhost:8080/update-json \
  -H "Content-Type: application/json" \
  -d '{"name": "Johann", "status": "pending", "draft": true}'

The response will look like this (timestamp will vary):

{"name":"Johann","status":"processed","lastUpdated":1700000000000}

Bonus: Type-Safe Approach with a DTO

If your JSON has a fixed structure, using a custom DTO (Data Transfer Object) is better for type safety. For example, if your input is user data, create a DTO class:

public class UserDto {
    private String name;
    private String status;
    private long lastUpdated;

    // Add getters and setters, or use Lombok @Data to auto-generate them
}

Then modify the controller method to work with the DTO (Spring handles JSON serialization/deserialization automatically):

@PostMapping("/update-user")
public UserDto updateUser(@RequestBody UserDto user) {
    user.setStatus("processed");
    user.setLastUpdated(System.currentTimeMillis());
    return user;
}

内容的提问来源于stack exchange,提问作者Johann M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:30:54