[英]Gson.fromJson stuck on line
我正在使用 gson 来解析来自 HttpExchange object 的数据。但是,在我的 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
}
private HashMap<ArrayList<Integer>, book> sections;
Gson 认为您的sections
字段应该是 map...
"sections": [
...但是您有一个项目数组,每个项目都是一个 object,其中包含chapters
(整数数组)和book
(字符串)。 Map
和HashMap
采用两个通用的 arguments,其中第一个是键,第二个是值。 在 JSON 中,键几乎总是一个String
,就像在这个 JSON 中代表一个HashMap<String, Integer>
:
{
"abc": 123,
"def": 456
}
如果你想匹配你提供的 JSON,你需要的sections
看起来像这样:
public class Section {
private ArrayList<Integer> chapters;
private String book;
}
private ArrayList<Section> sections;
但是,在我的 IDE 中,我在使用
.fromjson
的那一行设置了一个断点,它永远不会越过那一行。
听起来您在评论中理解try
/ catch
,但是对于您的问题标题“stuck on line”和您问题中的这句话,我将在此处进行总结。
当 Java 应用程序中发生意外或错误时(如您的com.google.gson.JsonSyntaxException
中的“异常”),它将查找最近的封闭try
/ catch
块。 如果当前方法中没有,它将检查调用当前方法的方法,然后检查调用该方法的方法,依此类推。 Web 服务器应用程序通常有一个封闭的try
/ catch
,这将导致错误代码如 500,如果没有捕获到错误,它可能会终止程序。 您可以在Java 教程“什么是异常?”中了解有关异常的更多信息。 ,但它被“卡住”在该行的外观可能是它进入默认异常处理程序并且永远不会返回到“抛出异常”的方法的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.