【发布时间】:2020-06-06 20:52:29
【问题描述】:
我正在使用 gson 解析来自 HttpExchange 对象的数据。但是,在我的 IDE 中,我在使用 .fromjson 的行设置了一个断点,并且它永远不会超过该行。它只是一次又一次地回到它。
public void handle(HttpExchange exchange) throws IOException {
System.out.println("/createTest");
if (exchange.getRequestMethod().toLowerCase().equals("post")){
System.out.println("get request");
InputStream reqBody = exchange.getRequestBody();
String reqData = readString(reqBody);
Gson gson = new Gson();
TestRequest testRequest = new TestRequest();
System.out.println(reqData);
testRequest = gson.fromJson(reqData, TestRequest.class);
System.out.println("gson done");
//Get the test
TestService testService = new TestService();
TestResponse result = testService.execute(testRequest);}
这是 TestRequest.java 的更新 java
import Model.TestParameter;
import java.util.ArrayList;
import java.util.HashMap;
public class TestRequest {
private HashMap<ArrayList<Integer>, book> sections;
private int difficulty;
private boolean closedBook;
private int length;
private int assortment;
我使用 JSONlint 来检查我输入的 JSON 数据是否正确,确实如此。在这里,对于好奇的人:
{
"sections": [
{
"chapters": [
11,
12,
20,
21,
22
],
"book": "NEPHI1"
},
{
"chapters": [
20,
29
],
"book": "NEPHI2"
},
{
"chapters": [
1
],
"book": "OMNI"
}
],
"difficulty": 3,
"closedBook": true,
"length": 21,
"assortment": 0
}
【问题讨论】:
-
在非调试模式下运行时表现如何?
-
它抛出一个异常(我应该一直在做 try/catch)。这是一个例外:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 15 path $.sections[0]
-
你能用
TestRequest的源代码更新问题吗? -
完成!你可以在原帖中看到它
-
TestParameter.book的类型是什么?根据java模型看起来sections应该是TestParameter.book和List的映射,但是你的json有字符串"book": "NEPHI1",。尝试将此 json sn-p 更改为"book": ["NEPHI1"],
标签: javascript java json server gson