[英]Parsing JsonArray object from string into java object returning an exception
I want to be able to parse a response from the server into Java object using GSON, this is my code:我希望能够使用 GSON 将来自服务器的响应解析为 Java object,这是我的代码:
public void test() throws IOException {
Gson gson = new Gson();
final String uri= BASIC_URL.concat("/?apikey=772f549d&s=prom&y=2020");
simpleHttpClient = new SimpleHttpClient();
String response = simpleHttpClient.sendGetRequest(BASIC_URL.concat("/?apikey=772f549d&s=prom&y=2020"), headersMap);
JsonArray array = JsonHandler.asList(response, "Search");
Type listType = new TypeToken<List<ImdbClass>>(){}.getType();
Object obj = array.toString().getClass();
List<ImdbClass> lists = gson.fromJson(array.toString(), listType);
ImdbClass imdbClass = gson.fromJson(array.toString(), ImdbClass.class);
}
This is the desired Json Array string needed to be parsed into java object:这是需要解析为 java object 所需的 Json 数组字符串:
[
{
"Title": "Killer Prom",
"Year": "2020",
"imdbID": "tt10814308",
"Type": "movie",
"Poster": "N/A"
},
{
"Title": "Prom Knight",
"Year": "2020–",
"imdbID": "tt12143924",
"Type": "series",
"Poster": "https://m.media-amazon.com/images/M/MV5BMmRmN2QzMzQtYzdiZS00ZTEzLTg4ODgtYmY1MzBmMTM3ZGIzXkEyXkFqcGdeQXVyMTE1Mjg1MjU2._V1_SX300.jpg"
}
]
and this is my class to parse into:这是我的 class 解析为:
public class ImdbClass {
String Title;
String Year;
String imdbID;
String Type;
String Poster;
public ImdbClass(){}
}
But when I get to the last line in my code I get the following error:但是当我到达代码的最后一行时,出现以下错误:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
although my array is array of objects, what do I miss?虽然我的数组是对象数组,但我错过了什么?
The last line in your code is trying to deserialize from an array to a single object, ie代码中的最后一行试图从数组反序列化为单个 object,即
ImdbClass imdbClass = gson.fromJson(array.toString(), ImdbClass.class);
The exception is telling you that to perform a derserialization from a json string to ImdbClass.class, it wasn't expecting the JSON data to be in array format.例外是告诉您从 json 字符串到 ImdbClass.class 执行反序列化,它没想到 JSON 数据是数组格式。
The previous line,上一行,
List<ImdbClass> lists = gson.fromJson(array.toString(), listType);
looks like it should've already created you a List of ImdbClass - do you even need the last line?看起来它应该已经为您创建了一个 ImdbClass 列表 - 您甚至需要最后一行吗? You should be able to iterate the list and access them, eg您应该能够迭代列表并访问它们,例如
for (ImdbClass movie : lists)
{
// do something with movie
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.