38

我的控制器中有一个方法应该返回 JSON 格式的字符串。它为非原始类型返回 JSON:

@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> so() {
    return new ResponseEntity<String>("This is a String", HttpStatus.OK);
}

卷曲响应是:

This is a String
4

4 回答 4

65

问题的根源在于 Spring(通过ResponseEntityRestController和/或ResponseBody)将使用字符串的内容作为原始响应值,而不是将字符串视为要编码的 JSON 值。即使在控制器方法使用时也是如此produces = MediaType.APPLICATION_JSON_VALUE,就像这里的问题一样。

它本质上就像以下之间的区别:

// yields: This is a String
System.out.println("This is a String");

// yields: "This is a String"
System.out.println("\"This is a String\"");

第一个输出不能解析为 JSON,但第二个输出可以。

然而,类似的东西'"'+myString+'"'可能不是一个好主意,因为它不会处理字符串中双引号的正确转义,并且不会为任何此类字符串生成有效的 JSON。

处理此问题的一种方法是将字符串嵌入到对象或列表中,这样您就不会将原始字符串传递给 Spring。但是,这会改变您的输出格式,如果这是您想要做的,实际上没有充分的理由不能返回正确编码的 JSON 字符串。如果这是您想要的,最好的处理方法是通过 JSON 格式化程序,例如JsonGoogle Gson。以下是 Gson 的外观:

import com.google.gson.Gson;

@RestController
public class MyController

    private static final Gson gson = new Gson();

    @RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    ResponseEntity<String> so() {
        return ResponseEntity.ok(gson.toJson("This is a String"));
    }
}
于 2017-03-16T14:32:39.013 回答
20
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
    return "This is a String";
}
于 2013-08-22T16:21:57.470 回答
2
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) throws JSONException {
    JSONObject resp = new JSONObject();
    resp.put("status", 0);
    resp.put("id", id);

    return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}
于 2020-07-10T16:24:30.307 回答
0

另一种解决方案是为 使用包装器String,例如:

public class StringResponse {
    private String response;
    public StringResponse(String response) {
        this.response = response;
    }
    public String getResponse() {
        return response;
    }
}

然后在控制器的方法中返回它:

ResponseEntity<StringResponse>
于 2020-01-20T11:51:55.510 回答