我对Java很新,我在过去的几个小时里一直试着寻找答案,到目前为止我什么都没有。
我正在使用项目的诺贝尔奖API ,当我尝试从Json流转换为类时出现错误。
我在流中读取的代码是:
Gson gson = new Gson();
String sURL = "http://api.nobelprize.orgv1/laureate.json?bornCountry=Canada"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
LaureatesMain person = gson.fromJson(rootobj, LaureatesMain.class);
System.out.println(person);
}
我还没有检查来自流的错误。
我正在看的json流看起来像这样:
{
"laureates": [
{
"id": "140",
// MORE STUFF
"prizes": [
{
"year": "1990",
// MORE STUFF
"affiliations": [
{
"name": "Stanford University",
"city": "Stanford, CA",
"country": "USA"
}
]
}
]
}
]
}
我有一个获奖者,奖品和附属机构的课程,当它像Json一样在Json上运行时,我没有任何问题,它可以很好地进入课程。
我遇到的问题是,如果附属关系中没有条目,那么由于某种原因,API将{}翻转到[]并给我以下内容:
{
"laureates": [
{
"id": "140",
// MORE STUFF
"prizes": [
{
"year": "1990",
// MORE STUFF
"affiliations": [[]
]
}
]
}
]
}
当我在这个上运行时,我得到Expected BEGIN_OBJECT
但在路径<{1}}
BEGIN_ARRAY
我已经尝试过更改$.laureates[###].prizes[0].affiliations[0]
并尝试拦截Json并在进入GsonBuilder
之前更改它,但到目前为止没有任何对我有用。
我无法控制从API获得的内容。我可以处理它是一个空类对象或最终结构中的空值。这是项目的一个相当早的迭代,但到目前为止,这个问题阻止我继续进行其他事情。
由于
答案 0 :(得分:0)
回答我自己的问题,以便我可以关闭它。
我最终使用了Type Adapter,感谢您指导我。一旦我知道我在寻找什么,就不会太难。
在以下java文档中找到了非常好的信息:
https://google.github.io/gson/apidocs/com/google/gson/TypeAdapter.html
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/stream/JsonReader.html