3
I need to deserialize JSON for a generic list, but I’m having an error that I believe is in the conversion:
Method call:
AtualizarJSON at = (AtualizarJSON) DeserializaConsulta(AtualizarJSON.class, resultadoJSON);
Method:
private <T> List<T> DeserializaConsulta(Class<T> tipo, String resultadoJSON) throws JSONException {
if (resultadoJSON != null) {
return Arrays.asList(new Gson().fromJson(resultadoJSON, tipo));
}
return null;
}
Request at the WS:
private String ConsultarOuBaixarAtualizacoes(String urlT) throws IOException {
InputStream is = null;
try {
URL url = new URL(urlT);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is, "UTF-8");
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Caused by: com.google.gson.stream.Malformedjsonexception: Use Jsonreader.setLenient(true) to Accept malformed JSON at line 1 column 126
I believe that this solution is not ideal, because there must be a way to solve this problem by setting the types as I have seen in some examples, but I could not find examples for this case where I pass the type by parameter.
Could put a sample of JSON?
– Wakim
I’ve had problems with Gson and generic list, but I do not remember what it was, I think it is not possible to do the way you want (I may be wrong, tomorrow I see my project). However your error message indicates a problem even before the JSON conversion attempt, apparently you formed it wrong, try to check for errors in it. How it was generated?
– Math
I’ll put his return here, probably this is it, it comes correctly but the end of it comes a lot of weird characters
– Luiz Negrini
Place the sample within your question, because it is breaking the layout of the site hehe. Probably this must be some encoding problem. Try to check if the encoding of the answer is the same as your client expects. And I believe that by hitting this you don’t even need to use the
setLenient
.– Wakim
@Math can not put the sample there, can not edit =/... put a return print via browser, it does not return this string ae... tested in 2 browsers.
– Luiz Negrini
@Wakim sure I’ll see it! Thanks!
– Luiz Negrini
@Wakim can check the request if there is something wrong? I added the question.
– Luiz Negrini
I believe it’s the
buffer
. Why don’t you use aBufferedReader
to read all lines (using aStringBuilder
)? 'Cause you’re probably having oneString
with 2048 characters where 60% is junk (old memory data).– Wakim
@Wakim poe as an answer! I saw an example like this and I couldn’t do it. Thanks!
– Luiz Negrini