java - HTTP 错误代码 415 - JAVA 中的 JSON 数组

标签 java arrays json dialogflow-es jettison

我正在尝试通过 JAVA 生成并发送 JSON 文件,当我尝试添加带有数组的嵌套对象以适应应用程序的协议(protocol)(这对问题并不重要)时,java 程序无法发送文件,因为 HTTP 错误,代码 415(不支持的媒体类型),这很奇怪,因为当我将生成的 JSON 复制到目标应用程序(Google 的 DialogFlow)中时,它可以工作。换句话说,JSON 是有功能的,但 JAVA(版本 1.8)无法识别它。有谁知道为什么会发生这种情况?

当 JSON 文件中不包含 JSONArray 的部分时,发送请求不会出现问题(请参阅下面的代码)。我尝试将内容类型从“application/json;charset=utf8”更改为“application/json;charset=utf-8”或“application/json”,但没有任何效果(这部分未包含在代码中,因为导致 JSON 无法工作的更改位于下面的 block 中)。

部分不工作:

 static JSONObject messageToJSON()
 {
 JSONObject requestJson = new JSONObject();
 JSONObject meta= new JSONObject();
 JSONObject payload= new JSONObject();
 JSONArray arrayJson = new JSONArray();
 String messageData="My Message";    
 try
 {
 requestJson.put("message", messageData);
 requestJson.put("messageType", "html");
 payload.put("title",  "Thanks");
 payload.put("message",  "Thank you");
 arrayJson.put(payload);
 meta.put("contentType", "300");
 meta.put("templateId", "6");
 meta.put("contentType", "300");
 meta.put("payload", arrayJson);
 requestJson.put("metadata", meta);
 System.out.println(requestJson.toString());
 }
 catch (JSONException e)
 {
 e.printStackTrace();
 }
 return requestJson;
 }

工作部分(没有 JSON 中的额外层,例如有效负载 JSON 对象和 arrayJson JSON 数组):

 static JSONObject messageToJSON()
 {
 JSONObject requestJson = new JSONObject();
 JSONObject meta= new JSONObject();
 JSONObject payload= new JSONObject();
 JSONArray arrayJson = new JSONArray();
 String messageData="My Message";    
 try
 {
 requestJson.put("message", messageData);
 requestJson.put("messageType", "html");
 meta.put("contentType", "300");
 meta.put("templateId", "6");
 meta.put("contentType", "300");
 requestJson.put("metadata", meta);
 System.out.println(requestJson.toString());
 }
 catch (JSONException e)
 {
 e.printStackTrace();
 }  
 return requestJson;
 }

最佳答案

好的,我发现问题了。我应该将 arrayJson 从 JSONArray 类型转换为字符串。 换句话说,而不是

meta.put("payload", arrayJson);

我应该有

meta.put("payload", arrayJson.toString());

或者从头开始将 arrayJson 设为字符串格式。

关于java - HTTP 错误代码 415 - JAVA 中的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54744477/

相关文章:

java - Tesseract For Java 为可执行 jar 设置 Tessdata_Prefix

c - 打印更新的阵列板

json - Erlang JSON 库 : serialization performance?

javascript - 如何在javascript中初始化4d数组?

java - 字符串到 int 数组 [][] - JAVA

javascript - 使用 Ajax 的地下气象 API

c# - 试图轻松保存游戏数据,需要帮助将对象统一添加到 json 文件

java - 使用不可观察的数据填充 TableView

java - 无法实例化类 models.Customer。它必须有一个默认构造函数

java - Gson.fromJson() 不解析日期字段