Gson.fromJson卡在行上

问题描述 投票:0回答:1

我正在使用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的更新版。

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
}
javascript java json server gson
1个回答
1
投票
private HashMap<ArrayList<Integer>, book> sections;

Gson认为你的 sections 字段应该是一个地图... ...但你却有一个项目数组,每个项目都是一个对象。

"sections": [

...但你有一个项目数组,每个项目都是一个带有 chapters (整数组)和 book (a String)。MapHashMap 取两个通用参数,其中第一个是键,第二个是值。在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但它永远不会越过那条线

听起来你好像明白了 trycatch 的评论中,但对于你的问题标题 "卡在线上 "和你问题中的这句话,我在这里总结一下。

当Java应用程序中发生了一些意想不到的事情或错误时,(如你的问题中的 "异常")。com.google.gson.JsonSyntaxException),它将寻找最近的包围的 trycatch 块。如果当前方法中没有,它将检查调用当前方法的方法,然后检查调用了 方法,等等。Web服务器应用程序通常有一个封闭的 trycatch 将导致一个错误代码,如500,如果根本没有发现错误,将可能终止程序。你可以在 "异常 "一书中了解更多关于 "异常 "的信息。Java教程 "什么是异常?",但它 "卡住 "在那一行的表象很可能是由于它进入了默认的异常处理程序,并且再也没有返回到 "抛出 "异常的方法。

© www.soinside.com 2019 - 2024. All rights reserved.