how gson can identify between a class instance and an array? - java

I send some data to my server and get a response.
In case there was an error the response is a class instance:
{
errorCode (int),
errorMsg (String)
}
In a success case the response is an items array.
I have tried to run the following code and got an error:
code:
private void afterServerOfferResponse(final Gson gson,
String result) {
ServerErrorMessage serverErrorMessage = gson.fromJson(
result, ServerErrorMessage.class);
if (serverErrorMessage.errorCode == 0) {
Type collectionType = new TypeToken<ArrayList<Offer>>() {
}.getType();
mOffersList = gson.fromJson(result, collectionType);
mAdapter = new ImageAdapter(OffersListActivity.this,
mOffersList);
mListView.setAdapter(mAdapter);
error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
how would you check for an error case without changing the server response too much?

Add a try-catch block to handle the exception. Only when you try to parse the data, it will be validated if its valid JSON response or error.
First try to parse Array Class instance and if JSON exception , then parse with ServerErrorMessage class
Add like this, and handle the exception when Syntax Exception
try{
ServerErrorMessage serverErrorMessage = gson.fromJson(
result, ServerErrorMessage.class);
}catch (JsonSyntaxException e){
// handle the exception
}
catch (JsonIOException e){
// handle the exception
}
catch (JsonParseException e){
// handle the exception
}catch (IOException e){
// handle the exception
}
Another way is to use org.json.JSONObject like this
private boolean isValidJsonResponse(String responseString){
try {
new JSONObject(responseString);
return true;
} catch(JSONException e) {
return false;
}
}

Related

How to Read Large Json File in chunks

I am using below JSON format:
[{object1},{object2},{object3}...]
I am reading a JSON file object wise means one by one (object by object) and my below code working fine.
I want to read it in chunks(at a time 10 objects). I have tried a lot but I am not getting any solution (without using Spring Batch). Can anybody please help me how to read in chunks
#Component
public class PdpiRunner3 implements CommandLineRunner {
#Override
public void run(String... args) throws Exception {
try {
JsonReader jsonReader = new JsonReader(new InputStreamReader(new ClassPathResource("/json/trades2.json").getInputStream(),StandardCharsets.UTF_8));
Gson gson = new GsonBuilder().create();
jsonReader.beginArray();
while (jsonReader.hasNext()) { // next json array element
PDPIfiles json = gson.fromJson(jsonReader, PDPIfiles.class);
if (json != null) {
System.out.println(json);
}
}
jsonReader.endArray();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Is it possible to read json element In Chunk without spring Batch pleas help ?

try catch code reading JSON file Android

having some serious problem when trying to read a local JSON file. I've looked everywhere for many days now and the best and farthest I could get was copying from Faizan's answer.
Reading a json file in Android
How come that Android Studio doesn't let me generate the second try-catch code block here?
Help and advice are very much appreciated!!
This is My code
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("names.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
How come that Android Studio doesn't let me generate the second
try-catch code block here?
Simply, because your code is not inside a method.
Doing something like below should solve the error.
public void someMethodIdentifier(){ // doesn't have to be void return type, you know better than me what type you want to return.
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
Note - from the looks of the statements that's contained within the try block I think you intended to return some data? if that's the case just replace the void return type with the appropriate return type and return that data.

Jackson: How to check if it is possible to parse text to POJO without error handling?

If I want to convert a string to POJO via ObjectMapper I need to wrap up my code every time with try-catch block and ignore errors.
ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(body, A.class);
} catch (IOException e) {
// NOP
}
try {
mapper.readValue(body, B.class);
} catch (IOException e) {
// NOP
}
throw new RuntimeException("Could not parse the response body");
Is it possible to check before invocation of method readValue if a string convertible to POJO class?
Yes but It could return null.
Configuring object mapper to not fail for unknown properties would do it.
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
A a = mapper.readValue(body, A.class);
org.codehaus.jackson.map.DeserializationConfig

Log4j1.x LoggingEnvent : can't get the Object

I use Log4j1.x for sending by Socket (SocketAppender in AsyncAppender) some loggingEvent.
I send a personnal object Serializable in the LoggingEvent message.
In the Chainsaw (example of server wide), I would like to recover my personnal object.
I can show the class name (event.getMessage().toString())
I can get the throwable
My personnal object is in a library, the same in the both projects.
My problem : I can't instance the message.
the error :
Exception in thread "Thread-5" java.lang.ClassCastException: java.lang.String cannot be cast to com.my.MyPersonnalObject
at org.apache.log4j.chainsaw.LoggingReceiver$Slurper.run(LoggingReceiver.java:80)
at java.lang.Thread.run(Unknown Source)
How can I rescure my Object ?
Thanks,
I found a simply way.
Override the toString of MyPersonnalObject to return an JSON value :
#Override
public String toString()
{
String str = "";
try
{
str = objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e)
{
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
str = "ERROR JSON" + errors.toString();
}
return str;
}
Then, on the other side, use :
public static MyPersonnalObject rescure(String jsonStr)
{
MyPersonnalObject b = null;
try
{
JsonParser jsonParser = jsonFactory.createParser(jsonStr);
b = objectMapper.readValue(jsonParser, MyPersonnalObject.class);
} catch (JsonParseException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return b;
}

Help with JSON error handling and google translate api

I'm currently parsing a JSON response from the Google Translate API. I'm able to do this with no problem. Seeing as how I don't have a lot of XML experience (I'm more of an XML guy), I'm having trouble figuring out how to implement some error handling in my JSON parsing. I am using the JSON j2me library.
Here is a successful response:
{"responseData": {"translatedText":"Teks te vertaal ...","detectedSourceLanguage":"en"}, "responseDetails": null, "responseStatus": 200}
And here is an unsuccessful response:
{"responseData": null, "responseDetails": "could not reliably detect source language", "responseStatus": 400}
So, if the translation is unsuccessful, I want to put the value of "responseDetails" into a string. Here is my parsing code, which is not currently parsing out responseDetails correctly. Instead, the "catch" of the "try" is being caught.
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
JSONObject responseData = responseObject
.getJSONObject("responseData");
if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
} else {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate!");
}
Can anyone see where I'm going wrong?
Thanks!
Since you say the catch block is being triggered, I'd start debugging by looking at what Exception is being thrown. You could simply append your alert string to include e.toString().
So change your alert in the catch block to be:
Notify.alert("Unable to translate! " + e.toString());
And see what the actual error that's being thrown is.
Based on your comment, yes it looks like it's trying to create a JSONObject on a null value, so nest another try/catch block and parse it accordingly that way.
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
/* Try create a new JSON object from the
* responseData object. If it fails,
* display an alert */
try {
JSONObject responseData = responseObject
.getJSONObject("responseData");
if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
}
} catch (Exception e) {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate outer block!");
}

Categories