Resolving JSON Library Conflicts in Java Code
这些编译错误是因为在代码中混用了不同版本的 JSON 库。VoiceService.java 中同时使用了 org.json.JSONObject 和 com.alibaba.fastjson2.JSONObject,但它们的 API 不同。
这是主要的几个问题:
-
构造函数不一致:
org.json.JSONObject有JSONObject(String)构造函数,而com.alibaba.fastjson2.JSONObject没有 -
方法名不一致:
org.json.JSONObject使用has()方法,而com.alibaba.fastjson2.JSONObject使用containsKey() -
类型不匹配:不能将
com.alibaba.fastjson2.JSONObject赋值给org.json.JSONObject
以下是修复方案:
方案1:统一使用 fastjson2(推荐)
修改 VoiceService.java
package com.alatus.salesSystem.service;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray; // 如果需要的话
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
public class VoiceService {
private final OkHttpClient httpClient = new OkHttpClient();
@Value("${dashscope.api.key}")
private String apiKey;
@Value("${dashscope.base.url}")
private String baseUrl;
@Value("${ai.model.tts}")
private String ttsModel;
@Value("${ai.model.asr}")
private String asrModel;
@Value("${voice.storage.path:./uploads/voice/}")
private String voiceStoragePath;
/**
* 声音复刻(可选功能)- 使用阿里百炼通义千问声音复刻
*/
public String uploadVoiceStyle(String customName, String text, MultipartFile audioFile) throws IOException {
String url = baseUrl + "/audio/voice-enrollment";
// 读取音频文件并转换为base64
byte[] audioBytes = audioFile.getBytes();
String audioBase64 = Base64.getEncoder().encodeToString(audioBytes);
JSONObject requestBody = new JSONObject();
requestBody.put("model", "qwen-voice-enrollment");
requestBody.put("custom_name", customName);
requestBody.put("text", text);
requestBody.put("audio", audioBase64);
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(
requestBody.toString(),
MediaType.parse("application/json")
))
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful() || response.body() == null) {
String errorBody = response.body() != null ? response.body().string() : "无响应体";
throw new RuntimeException("上传语音风格失败: " + response.code() + " - " + errorBody);
}
String responseBody = response.body().string();
JSONObject jsonResponse = JSON.parseObject(responseBody); // 使用 fastjson2 的 parseObject
return jsonResponse.getString("voice_id");
}
}
/**
* 保存音频文件到本地
*/
public String saveAudioFile(byte[] audioData, String filename) throws IOException {
File storageDir = new File(voiceStoragePath);
if (!storageDir.exists()) {
storageDir.mkdirs();
}
String filePath = voiceStoragePath + filename;
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(audioData);
}
return "/voice/" + filename; // 返回相对路径
}
/**
* 生成唯一文件名
*/
public String generateAudioFilename() {
return UUID.randomUUID().toString() + ".mp3";
}
/**
* 文本转语音 - 使用DashScope原生API
*/
public byte[] textToSpeech(String text, String voiceStyleUri) throws IOException {
String url = baseUrl + "/services/aigc/audio/tts/v1/audio";
JSONObject input = new JSONObject();
input.put("text", text);
Map<String, Object> parameters = new HashMap<>();
parameters.put("model", ttsModel);
parameters.put("format", "mp3");
parameters.put("sample_rate", 32000);
parameters.put("speed", 1.0);
if (voiceStyleUri != null && !voiceStyleUri.isEmpty()) {
parameters.put("voice", voiceStyleUri);
} else {
parameters.put("voice", "anna");
}
JSONObject requestBody = new JSONObject();
requestBody.put("input", input);
JSONObject params = new JSONObject();
parameters.forEach(params::put);
requestBody.put("parameters", params);
RequestBody body = RequestBody.create(
requestBody.toJSONString(), // fastjson2 的方法
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful() || response.body() == null) {
String errorBody = response.body() != null ? response.body().string() : "无响应体";
throw new RuntimeException("文本转语音失败: " + response.code() + " - " + errorBody);
}
return response.body().bytes();
}
}
/**
* 语音转文本 - 使用DashScope原生API
*/
public String speechToText(MultipartFile audioFile) throws IOException {
String url = baseUrl + "/services/aigc/audio/asr/v1/audio";
// 创建临时文件
File tempFile = File.createTempFile("audio_", ".mp3");
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(audioFile.getBytes());
}
JSONObject input = new JSONObject();
input.put("audio", Base64.getEncoder().encodeToString(audioFile.getBytes()));
Map<String, Object> parameters = new HashMap<>();
parameters.put("model", asrModel);
parameters.put("response_format", "json");
JSONObject requestBody = new JSONObject();
requestBody.put("input", input);
JSONObject params = new JSONObject();
parameters.forEach(params::put);
requestBody.put("parameters", params);
RequestBody body = RequestBody.create(
requestBody.toJSONString(), // 使用 fastjson2 的方法
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful() || response.body() == null) {
String errorBody = response.body() != null ? response.body().string() : "无响应体";
throw new RuntimeException("语音转文本失败: " + response.code() + " - " + errorBody);
}
String responseBody = response.body().string();
JSONObject jsonResponse = JSON.parseObject(responseBody); // 使用 fastjson2 的 parseObject
// 注意:fastjson2 使用 getIntValue 而不是 getInteger
if (jsonResponse.getIntValue("status_code") == 200) {
JSONObject output = jsonResponse.getJSONObject("output");
JSONObject result = output.getJSONObject("result");
return result.getString("text");
}
throw new RuntimeException("语音识别失败: " + jsonResponse.getString("message"));
} finally {
// 删除临时文件
tempFile.delete();
}
}
}
修改 ImageGenerationService.java
还需要修改 ImageGenerationService.java 中的几个问题:
// 修改以下方法中的 JSON 相关代码
/**
* 提交阿里百炼图片生成请求
*/
private List<String> submitAliBailianImageGeneration(
Map<String, Object> requestBody, String taskId, int maxRetries) throws IOException {
String url = baseUrl + "/images/generations";
log.info("调用阿里百炼图片生成API: {}", url);
// 使用 fastjson2 的 JSONObject
JSONObject json = new JSONObject(requestBody);
RequestBody body = RequestBody.create(
json.toJSONString(), // 使用 toJSONString()
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.addHeader("X-Request-Id", "img_" + System.currentTimeMillis())
.build();
IOException lastException = null;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
try {
log.info("任务 {}: 图片生成API调用第{}次尝试", taskId, attempt);
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
String errorBody = response.body() != null ? response.body().string() : "无响应体";
log.error("图片生成API请求失败,状态码: {}, 响应: {}", response.code(), errorBody);
// 使用 fastjson2 的 parseObject
JSONObject errorJson = JSON.parseObject(errorBody);
if (errorJson.containsKey("error")) { // 使用 containsKey 而不是 has
String errorMsg = errorJson.getJSONObject("error").getString("message");
throw new RuntimeException("图片生成API错误: " + errorMsg);
}
throw new RuntimeException("图片生成请求失败: " + response.code() + " - " + errorBody);
}
if (response.body() == null) {
throw new RuntimeException("图片生成响应体为空");
}
String responseBody = response.body().string();
JSONObject jsonResponse = JSON.parseObject(responseBody); // 使用 parseObject
if (!jsonResponse.containsKey("data")) { // 使用 containsKey
log.error("API响应缺少data字段: {}", jsonResponse.toJSONString(2)); // 使用 toJSONString
throw new RuntimeException("API响应格式错误,缺少data字段");
}
JSONArray images = jsonResponse.getJSONArray("data");
return images.toList(String.class); // 使用 toList 并指定类型
}
} catch (IOException e) {
// ... 其他代码不变
}
}
throw new IOException("图片生成失败,无可用重试", lastException);
}
/**
* 提交图片生成请求
*/
private List<String> submitImageGeneration(Map<String, Object> requestBody) throws IOException {
String url = baseUrl + "/images/generations";
log.info("调用图片生成API: {}", url);
// 使用 fastjson2 的 JSONObject
JSONObject json = new JSONObject(requestBody);
RequestBody body = RequestBody.create(
json.toJSONString(), // 使用 toJSONString
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.addHeader("X-Request-Id", "img_" + System.currentTimeMillis())
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
String errorBody = response.body() != null ? response.body().string() : "无响应体";
log.error("图片生成API请求失败,状态码: {}, 响应: {}", response.code(), errorBody);
// 使用 fastjson2 的 parseObject
JSONObject errorJson = JSON.parseObject(errorBody);
if (errorJson.containsKey("error")) { // 使用 containsKey
String errorMsg = errorJson.getJSONObject("error").getString("message");
throw new RuntimeException("图片生成API错误: " + errorMsg);
}
throw new RuntimeException("图片生成请求失败: " + response.code() + " - " + errorBody);
}
if (response.body() == null) {
throw new RuntimeException("图片生成响应体为空");
}
String responseBody = response.body().string();
JSONObject jsonResponse = JSON.parseObject(responseBody); // 使用 parseObject
if (!jsonResponse.containsKey("images")) { // 使用 containsKey
log.error("API响应缺少images字段: {}", jsonResponse.toJSONString(2)); // 使用 toJSONString
throw new RuntimeException("API响应格式错误,缺少images字段");
}
JSONArray images = jsonResponse.getJSONArray("images");
return images.toList(String.class); // 使用 toList 并指定类型
}
}
/**
* 提交DashScope图片生成请求
*/
private List<String> submitDashScopeImageGeneration(
Map<String, Object> requestBody, String taskId, int maxRetries) throws IOException {
String model = (String) requestBody.get("model");
JSONObject input = (JSONObject) requestBody.get("input");
Map<String, Object> parameters = (Map<String, Object>) requestBody.get("parameters");
// 调用DashScope原生图片生成API
String response = apiHelper.callDashScopeImageApi(model, input, parameters);
// 解析响应
JSONObject jsonResponse = JSON.parseObject(response);
if (jsonResponse.getIntValue("status_code") == 200) { // 使用 getIntValue
JSONObject output = jsonResponse.getJSONObject("output");
JSONArray results = output.getJSONArray("results");
if (results != null && !results.isEmpty()) {
return results.toList(String.class); // 使用 toList 并指定类型
}
}
throw new RuntimeException("图片生成失败: " + jsonResponse.getString("message"));
}
方案2:统一使用 org.json
如果您想使用 org.json 而不是 fastjson2,可以:
-
移除 fastjson2 的依赖,只保留 org.json
-
修改所有
JSON.parseObject()为new JSONObject() -
修改所有
.toJSONString()为.toString() -
修改所有
.toList()调用
依赖配置
确保您的 pom.xml 或 build.gradle 中有正确的依赖:
Maven (使用 fastjson2):
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.51</version>
</dependency>
Maven (使用 org.json):
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
建议使用方案1(统一使用 fastjson2),因为:
-
fastjson2 性能更好
-
您的代码中已经大量使用了 fastjson2
-
fastjson2 有更好的类型安全性和更丰富的 API
我们有两个文件:VoiceService.java 和 ImageGenerationService.java。这些文件中存在一些编译错误,主要是由于使用了错误的JSONObject类。
在VoiceService.java中,我们混合使用了org.json.JSONObject和com.alibaba.fastjson2.JSONObject。
而在ImageGenerationService.java中,我们主要使用了com.alibaba.fastjson2.JSONObject,但也有一些地方使用了org.json.JSONObject。
根据错误信息,我们需要统一使用一种JSONObject。由于项目中已经引入了com.alibaba.fastjson2,并且大部分代码使用了它,我们建议将org.json.JSONObject的使用替换为com.alibaba.fastjson2.JSONObject。
但是,请注意,在VoiceService.java中,我们使用了org.json.JSONObject的构造函数和toString方法,而fastjson2的JSONObject的构造函数和toString方法有所不同。
具体问题如下:
在VoiceService.java中:
-
第166行:new JSONObject(errorBody) // 这里使用了org.json.JSONObject的构造函数,但错误提示无法解析构造函数,可能是因为没有这样的构造函数或者导入了错误的类。
-
第167行:jsonResponse.has("error") // org.json.JSONObject有has方法,但fastjson2的JSONObject没有has方法,而是用containsKey。
-
第180行:new JSONObject(errorBody) // 同上
-
第182行:jsonResponse.has("error") // 同上
-
第183行:jsonResponse.toString(2) // org.json.JSONObject的toString(int indentSpaces)方法,fastjson2的JSONObject没有这个方法,我们可以用toJSONString(int indentSpaces)代替。
-
第188行:images.toList() // org.json.JSONArray的toList()方法,fastjson2的JSONArray没有这个方法,我们可以用toList(),但注意fastjson2的JSONArray有toList()方法吗?在fastjson2中,JSONArray实现了List接口,所以可以直接当作List使用,或者用toList()方法(如果存在的话)。实际上,fastjson2的JSONArray有toList()方法,但返回的是List<Object>,需要根据实际情况转换。
-
第129行:requestBody.toJSONString() // 这里使用的是org.json.JSONObject的toJSONString方法,但是org.json.JSONObject没有这个方法,应该是fastjson2的JSONObject的方法。所以这里应该使用fastjson2的JSONObject。
在ImageGenerationService.java中:
-
第606行:new JSONObject(errorBody) // 同样的问题
-
第607行:errorJson.has("error") // 同样的问题
-
第622行:new JSONObject(errorBody) // 同样的问题
-
第623行:jsonResponse.toString(2) // 同样的问题
-
第628行:images.toList() // 同样的问题
-
第787行:results.toList() // 同样的问题
另外,在VoiceService.java的第195行,我们将com.alibaba.fastjson2.JSONObject赋值给了org.json.JSONObject,导致类型不匹配。
为了解决这些问题,我们决定将所有org.json.JSONObject的引用替换为com.alibaba.fastjson2.JSONObject,并调整相应的方法调用。
修改步骤:
-
在VoiceService.java中,将import org.json.JSONObject;替换为import com.alibaba.fastjson2.JSONObject;和import com.alibaba.fastjson2.JSONArray;(如果需要)。
-
在ImageGenerationService.java中,我们已经使用了com.alibaba.fastjson2.JSONObject,但是有一些地方仍然使用了org.json.JSONObject,需要检查并替换。
但是,注意在VoiceService.java中,我们使用了org.json.JSONObject的构造函数,而fastjson2的JSONObject的构造函数不接受字符串。我们需要使用JSON.parseObject(String)来解析字符串。
具体修改:
对于VoiceService.java:
第166行:将
JSONObject errorJson = new JSONObject(errorBody);
改为:
JSONObject errorJson = JSON.parseObject(errorBody);
第167行:将
if (errorJson.has("error")) {
改为:
if (errorJson.containsKey("error")) {
第180行:同样改为JSON.parseObject(errorBody)
第182行:改为containsKey
第183行:将
log.error("API响应缺少data字段: {}", jsonResponse.toString(2));
改为:
log.error("API响应缺少data字段: {}", jsonResponse.toJSONString(2));
第188行:将
return images.toList().stream()
改为:
return images.stream() // 因为fastjson2的JSONArray实现了List接口,所以可以直接stream()
但是,注意第188行中的images是org.json.JSONArray,我们将其改为fastjson2的JSONArray后,就可以直接使用stream()方法了吗?是的,因为JSONArray实现了List接口。
但是,我们还需要修改第186行获取images的方式。原来使用org.json.JSONObject的getJSONArray方法,在fastjson2中同样有这个方法。
所以,我们将第186行改为:
JSONArray images = jsonResponse.getJSONArray("data");
但是,注意:在fastjson2中,getJSONArray返回的是com.alibaba.fastjson2.JSONArray。
同样,第195行:我们将
JSONObject jsonResponse = JSON.parseObject(responseBody);
改为使用fastjson2的JSONObject,因为我们已经改变了import。
第197行:将
if (jsonResponse.getInteger("status_code") == 200) {
改为:
if (jsonResponse.getIntValue("status_code") == 200) { // 或者使用getInteger,但fastjson2的JSONObject有getInteger方法吗?实际上,fastjson2的JSONObject有getInteger方法,但是返回Integer,也可以使用getIntValue返回int。
但是,注意:在fastjson2中,获取整数有多种方法,我们可以使用getIntValue("status_code")。
另外,第129行:将
JSON.toJSONString(requestBody)
改为:
requestBody.toJSONString() // 因为requestBody是fastjson2的JSONObject,所以有toJSONString方法。
但是,注意:在VoiceService.java的第129行,requestBody是org.json.JSONObject,我们将其改为fastjson2的JSONObject。
所以,我们需要将VoiceService.java中所有使用org.json.JSONObject的地方都改为com.alibaba.fastjson2.JSONObject。
由于修改较多,我们逐步修改。
首先,修改VoiceService.java的import部分:
删除import org.json.JSONObject;
添加import com.alibaba.fastjson2.JSONObject;
添加import com.alibaba.fastjson2.JSONArray;
然后,修改代码中org.json.JSONObject的用法。
由于fastjson2的JSONObject和JSONArray与org.json的用法不完全相同,我们需要仔细修改。
在VoiceService.java中,我们使用org.json.JSONObject创建对象,例如:
JSONObject requestBody = new JSONObject();
在fastjson2中,我们可以使用new JSONObject(),但是注意:fastjson2的JSONObject的put方法返回的是JSONObject本身,而org.json的put方法返回的是Object。
所以,我们可以这样修改:
例如,第48行:
JSONObject requestBody = new JSONObject();
requestBody.put("model", "qwen-voice-enrollment");
....
在fastjson2中,这同样有效。
但是,在VoiceService.java中,我们使用了org.json.JSONObject的toString方法,而fastjson2的JSONObject也有toString方法,但是toString(int indent)方法在fastjson2中为toJSONString(int indent)。
所以,我们需要将toString(2)改为toJSONString(2)。
另外,在VoiceService.java中,我们使用了org.json.JSONObject的getString、getJSONObject等方法,这些在fastjson2中同样存在。
但是,注意:在VoiceService.java的第197行,我们使用了getInteger,在fastjson2中,我们可以使用getIntValue。
现在,我们开始修改VoiceService.java:
-
修改import。
-
将第166行改为:JSONObject errorJson = JSON.parseObject(errorBody);
-
将第167行改为:if (errorJson.containsKey("error")) {
-
将第180行改为:JSONObject jsonResponse = JSON.parseObject(responseBody);
-
将第182行改为:if (!jsonResponse.containsKey("data")) {
-
将第183行改为:jsonResponse.toJSONString(2)
-
将第188行改为:return images.stream()... // 因为images已经是fastjson2的JSONArray,它实现了List接口,所以可以直接stream()
-
将第195行改为:JSONObject jsonResponse = JSON.parseObject(responseBody);
-
将第197行改为:if (jsonResponse.getIntValue("status_code") == 200) {
-
第129行:已经使用了JSON.toJSONString,但requestBody是org.json.JSONObject,我们需要将其改为fastjson2的JSONObject。但是,注意第129行在哪个方法中?在speechToText方法中,我们创建了一个org.json.JSONObject,现在要改为fastjson2的JSONObject。
实际上,在VoiceService.java中,我们有两个地方创建了JSONObject,一个在uploadVoiceStyle方法,一个在textToSpeech方法,一个在speechToText方法。
我们需要将这些方法中创建的org.json.JSONObject都改为com.alibaba.fastjson2.JSONObject。
由于修改涉及多个地方,我们逐个方法修改。
首先,在uploadVoiceStyle方法中,将JSONObject替换为com.alibaba.fastjson2.JSONObject。
然后,在textToSpeech方法中,同样替换。
最后,在speechToText方法中,同样替换。
注意:在speechToText方法中,我们使用了JSON.toJSONString,而requestBody已经是fastjson2的JSONObject,所以可以直接用requestBody.toJSONString()。
但是,为了统一,我们保留使用JSON.toJSONString(requestBody)也是可以的,因为fastjson2的JSONObject会被正确序列化。
现在,我们修改VoiceService.java:
由于修改较多,我们只列出需要修改的行和修改后的代码。
注意:在VoiceService.java中,我们使用了org.json.JSONObject的toJSONString方法,但org.json.JSONObject没有这个方法,所以我们需要将org.json.JSONObject的实例改为fastjson2的JSONObject。
我们决定将VoiceService.java中所有的org.json.JSONObject替换为com.alibaba.fastjson2.JSONObject。
修改如下:
-
修改import部分:
将import org.json.JSONObject;替换为import com.alibaba.fastjson2.JSONObject;和import com.alibaba.fastjson2.JSONArray; -
修改uploadVoiceStyle方法中的JSONObject为com.alibaba.fastjson2.JSONObject。
-
修改textToSpeech方法中的JSONObject为com.alibaba.fastjson2.JSONObject。
-
修改speechToText方法中的JSONObject为com.alibaba.fastjson2.JSONObject。
由于代码较长,我们只修改有错误的地方。
但是,为了确保代码正确,我们建议将整个文件中的org.json.JSONObject替换为com.alibaba.fastjson2.JSONObject。
由于时间关系,我们只修改错误提示的地方。
但是,请注意,在VoiceService.java中,我们使用了org.json.JSONObject的构造函数,而fastjson2的JSONObject没有构造函数接受字符串,所以我们需要用JSON.parseObject来解析字符串。
另外,在ImageGenerationService.java中,我们同样需要修改。
由于ImageGenerationService.java中已经使用了com.alibaba.fastjson2.JSONObject,但是有一些地方却使用了org.json.JSONObject的构造函数,这可能是错误的原因。
我们检查ImageGenerationService.java的import部分,发现已经导入了com.alibaba.fastjson2.JSONObject,但是代码中却使用了new JSONObject(errorBody)这样的构造函数,这实际上是调用了org.json.JSONObject的构造函数,因为fastjson2的JSONObject没有这个构造函数。
所以,我们需要将ImageGenerationService.java中所有使用new JSONObject(String)的地方改为JSON.parseObject(String)。
修改ImageGenerationService.java:
第606行:将
JSONObject errorJson = new JSONObject(errorBody);
改为:
JSONObject errorJson = JSON.parseObject(errorBody);
第607行:将
if (errorJson.has("error")) {
改为:
if (errorJson.containsKey("error")) {
第622行:将
JSONObject jsonResponse = new JSONObject(responseBody);
改为:
JSONObject jsonResponse = JSON.parseObject(responseBody);
第623行:将
if (!jsonResponse.has("images")) {
改为:
if (!jsonResponse.containsKey("images")) {
第624行:将
jsonResponse.toString(2)
改为:
jsonResponse.toJSONString(2)
第628行:将
images.toList().stream()
改为:
images.stream() // 因为fastjson2的JSONArray实现了List接口,可以直接stream()
第787行:将
results.toList().stream()
改为:
results.stream() // 同样,fastjson2的JSONArray实现了List接口
另外,在VoiceService.java中,我们还需要修改第195行,将
JSONObject jsonResponse = new JSONObject(responseBody);
改为:
JSONObject jsonResponse = JSON.parseObject(responseBody);
但是,VoiceService.java的第195行已经在第180行修改过了。
现在,我们修改VoiceService.java的第129行,将
JSON.toJSONString(requestBody)
改为:
requestBody.toJSONString() // 因为requestBody已经是fastjson2的JSONObject
但是,注意:在第129行,requestBody是org.json.JSONObject,我们需要将其改为fastjson2的JSONObject。
所以,我们需要修改speechToText方法中创建requestBody的部分,将其改为fastjson2的JSONObject。
修改VoiceService.java的speechToText方法:
将:
JSONObject requestBody = new JSONObject();
改为:
JSONObject requestBody = new JSONObject();
但是,注意:这里我们使用的是fastjson2的JSONObject,所以没有问题。
另外,在VoiceService.java的textToSpeech方法中,我们使用了org.json.JSONObject,也需要修改。
将:
JSONObject requestBody = new JSONObject();
改为使用fastjson2的JSONObject。
同样,在uploadVoiceStyle方法中,也将JSONObject改为fastjson2的JSONObject。
由于fastjson2的JSONObject的用法与org.json.JSONObject在put、get等方法上基本兼容,所以只需要改变构造方式即可。
但是,在textToSpeech方法中,我们使用了JSONObject的toJSONString方法,而org.json.JSONObject没有这个方法,所以必须改为fastjson2的JSONObject。
所以,我们修改VoiceService.java中所有出现JSONObject的地方,确保使用fastjson2的JSONObject。
由于修改较多,我们只修改了错误提示的地方,但是为了确保编译通过,可能需要修改更多。
现在,我们整理一下修改列表:
VoiceService.java:
-
修改import:去掉org.json.JSONObject,使用com.alibaba.fastjson2.JSONObject和com.alibaba.fastjson2.JSONArray。
-
修改uploadVoiceStyle方法中的JSONObject为com.alibaba.fastjson2.JSONObject。
-
修改textToSpeech方法中的JSONObject为com.alibaba.fastjson2.JSONObject。
-
修改speechToText方法中的JSONObject为com.alibaba.fastjson2.JSONObject。
-
将第166行改为:JSONObject errorJson = JSON.parseObject(errorBody);
-
将第167行改为:if (errorJson.containsKey("error")) {
-
将第180行改为:JSONObject jsonResponse = JSON.parseObject(responseBody);
-
将第182行改为:if (!jsonResponse.containsKey("data")) {
-
将第183行改为:jsonResponse.toJSONString(2)
-
将第188行改为:return images.stream()...
-
将第195行改为:JSONObject jsonResponse = JSON.parseObject(responseBody);
-
将第197行改为:if (jsonResponse.getIntValue("status_code") == 200) {
-
将第129行改为:requestBody.toJSONString()
ImageGenerationService.java:
-
将第606行改为:JSONObject errorJson = JSON.parseObject(errorBody);
-
将第607行改为:if (errorJson.containsKey("error")) {
-
将第622行改为:JSONObject jsonResponse = JSON.parseObject(responseBody);
-
将第623行改为:if (!jsonResponse.containsKey("images")) {
-
将第624行改为:jsonResponse.toJSONString(2)
-
将第628行改为:images.stream()...
-
将第787行改为:results.stream()...
由于代码量较大,我们只修改了这些错误提示的地方。但是,如果还有其他类似错误,请按照相同方式修改。
注意:在ImageGenerationService.java中,我们使用了org.json.JSONObject的has方法,需要改为containsKey。
另外,在ImageGenerationService.java中,我们使用了org.json.JSONObject的toString(int)方法,需要改为toJSONString(int)。
在VoiceService.java中,我们使用了org.json.JSONArray的toList()方法,在fastjson2中,JSONArray实现了List接口,所以可以直接当作List使用,不需要toList()方法。
但是,在ImageGenerationService.java中,我们也使用了toList()方法,同样需要改为stream()或者直接作为List使用。
由于时间关系,我们只修改了错误提示的地方。如果还有其他错误,请根据错误信息进行修改。
最后,请注意,在VoiceService.java中,我们使用了org.json.JSONObject的getJSONObject方法,在fastjson2中同样存在,所以不用修改。
但是,在VoiceService.java的第197行,我们使用了getInteger,在fastjson2中,我们可以使用getIntValue,或者getInteger(返回Integer)。我们改为getIntValue。
更多推荐



所有评论(0)